Skip to main content

icydb_core/db/query/intent/
query.rs

1//! Module: query::intent::query
2//! Responsibility: typed query-intent construction and planner handoff for entity queries.
3//! Does not own: runtime execution semantics or access-path execution behavior.
4//! Boundary: exposes query APIs and emits planner-owned compiled query contracts.
5
6#[cfg(feature = "sql")]
7use crate::db::query::plan::expr::ProjectionSelection;
8use crate::{
9    db::{
10        executor::{
11            BytesByProjectionMode, PreparedExecutionPlan,
12            assemble_aggregate_terminal_execution_descriptor,
13            assemble_load_execution_node_descriptor, assemble_load_execution_verbose_diagnostics,
14            planning::route::AggregateRouteShape,
15        },
16        predicate::{CoercionId, CompareOp, MissingRowPolicy, Predicate},
17        query::{
18            builder::{
19                AggregateExpr, PreparedFluentAggregateExplainStrategy,
20                PreparedFluentProjectionStrategy,
21            },
22            explain::{
23                ExplainAccessPath, ExplainAggregateTerminalPlan, ExplainExecutionNodeDescriptor,
24                ExplainExecutionNodeType, ExplainOrderPushdown, ExplainPlan, ExplainPredicate,
25            },
26            expr::{FilterExpr, SortExpr},
27            intent::{QueryError, model::QueryModel},
28            plan::{AccessPlannedQuery, GroupHavingExpr, LoadSpec, QueryMode, VisibleIndexes},
29        },
30    },
31    traits::{EntityKind, EntityValue, FieldValue, SingletonEntity},
32    value::Value,
33};
34use core::marker::PhantomData;
35
36///
37/// StructuralQuery
38///
39/// Generic-free query-intent core shared by typed `Query<E>` wrappers.
40/// Stores model-level key access as `Value` so only typed key-entry helpers
41/// remain entity-specific at the outer API boundary.
42///
43
44#[derive(Clone, Debug)]
45pub(in crate::db) struct StructuralQuery {
46    intent: QueryModel<'static, Value>,
47}
48
49impl StructuralQuery {
50    #[must_use]
51    pub(in crate::db) const fn new(
52        model: &'static crate::model::entity::EntityModel,
53        consistency: MissingRowPolicy,
54    ) -> Self {
55        Self {
56            intent: QueryModel::new(model, consistency),
57        }
58    }
59
60    // Rewrap one updated generic-free intent model back into the structural
61    // query shell so local transformation helpers do not rebuild `Self`
62    // ad hoc at each boundary method.
63    const fn from_intent(intent: QueryModel<'static, Value>) -> Self {
64        Self { intent }
65    }
66
67    // Apply one infallible intent transformation while preserving the
68    // structural query shell at this boundary.
69    fn map_intent(
70        self,
71        map: impl FnOnce(QueryModel<'static, Value>) -> QueryModel<'static, Value>,
72    ) -> Self {
73        Self::from_intent(map(self.intent))
74    }
75
76    // Apply one fallible intent transformation while keeping result wrapping
77    // local to the structural query boundary.
78    fn try_map_intent(
79        self,
80        map: impl FnOnce(QueryModel<'static, Value>) -> Result<QueryModel<'static, Value>, QueryError>,
81    ) -> Result<Self, QueryError> {
82        map(self.intent).map(Self::from_intent)
83    }
84
85    #[must_use]
86    const fn mode(&self) -> QueryMode {
87        self.intent.mode()
88    }
89
90    #[must_use]
91    fn has_explicit_order(&self) -> bool {
92        self.intent.has_explicit_order()
93    }
94
95    #[must_use]
96    pub(in crate::db) const fn has_grouping(&self) -> bool {
97        self.intent.has_grouping()
98    }
99
100    #[must_use]
101    const fn load_spec(&self) -> Option<LoadSpec> {
102        match self.intent.mode() {
103            QueryMode::Load(spec) => Some(spec),
104            QueryMode::Delete(_) => None,
105        }
106    }
107
108    #[must_use]
109    pub(in crate::db) fn filter(mut self, predicate: Predicate) -> Self {
110        self.intent = self.intent.filter(predicate);
111        self
112    }
113
114    fn filter_expr(self, expr: FilterExpr) -> Result<Self, QueryError> {
115        self.try_map_intent(|intent| intent.filter_expr(expr))
116    }
117
118    fn sort_expr(self, expr: SortExpr) -> Result<Self, QueryError> {
119        self.try_map_intent(|intent| intent.sort_expr(expr))
120    }
121
122    #[must_use]
123    pub(in crate::db) fn order_by(mut self, field: impl AsRef<str>) -> Self {
124        self.intent = self.intent.order_by(field);
125        self
126    }
127
128    #[must_use]
129    pub(in crate::db) fn order_by_desc(mut self, field: impl AsRef<str>) -> Self {
130        self.intent = self.intent.order_by_desc(field);
131        self
132    }
133
134    #[must_use]
135    pub(in crate::db) fn distinct(mut self) -> Self {
136        self.intent = self.intent.distinct();
137        self
138    }
139
140    #[cfg(feature = "sql")]
141    #[must_use]
142    pub(in crate::db) fn select_fields<I, S>(mut self, fields: I) -> Self
143    where
144        I: IntoIterator<Item = S>,
145        S: Into<String>,
146    {
147        self.intent = self.intent.select_fields(fields);
148        self
149    }
150
151    #[cfg(feature = "sql")]
152    #[must_use]
153    pub(in crate::db) fn projection_selection(mut self, selection: ProjectionSelection) -> Self {
154        self.intent = self.intent.projection_selection(selection);
155        self
156    }
157
158    pub(in crate::db) fn group_by(self, field: impl AsRef<str>) -> Result<Self, QueryError> {
159        self.try_map_intent(|intent| intent.push_group_field(field.as_ref()))
160    }
161
162    #[must_use]
163    pub(in crate::db) fn aggregate(mut self, aggregate: AggregateExpr) -> Self {
164        self.intent = self.intent.push_group_aggregate(aggregate);
165        self
166    }
167
168    #[must_use]
169    fn grouped_limits(mut self, max_groups: u64, max_group_bytes: u64) -> Self {
170        self.intent = self.intent.grouped_limits(max_groups, max_group_bytes);
171        self
172    }
173
174    pub(in crate::db) fn having_group(
175        self,
176        field: impl AsRef<str>,
177        op: CompareOp,
178        value: Value,
179    ) -> Result<Self, QueryError> {
180        let field = field.as_ref().to_owned();
181        self.try_map_intent(|intent| intent.push_having_group_clause(&field, op, value))
182    }
183
184    pub(in crate::db) fn having_aggregate(
185        self,
186        aggregate_index: usize,
187        op: CompareOp,
188        value: Value,
189    ) -> Result<Self, QueryError> {
190        self.try_map_intent(|intent| {
191            intent.push_having_aggregate_clause(aggregate_index, op, value)
192        })
193    }
194
195    pub(in crate::db) fn having_expr(self, expr: GroupHavingExpr) -> Result<Self, QueryError> {
196        self.try_map_intent(|intent| intent.push_having_expr(expr))
197    }
198
199    #[must_use]
200    fn by_id(self, id: Value) -> Self {
201        self.map_intent(|intent| intent.by_id(id))
202    }
203
204    #[must_use]
205    fn by_ids<I>(self, ids: I) -> Self
206    where
207        I: IntoIterator<Item = Value>,
208    {
209        self.map_intent(|intent| intent.by_ids(ids))
210    }
211
212    #[must_use]
213    fn only(self, id: Value) -> Self {
214        self.map_intent(|intent| intent.only(id))
215    }
216
217    #[must_use]
218    pub(in crate::db) fn delete(mut self) -> Self {
219        self.intent = self.intent.delete();
220        self
221    }
222
223    #[must_use]
224    pub(in crate::db) fn limit(mut self, limit: u32) -> Self {
225        self.intent = self.intent.limit(limit);
226        self
227    }
228
229    #[must_use]
230    pub(in crate::db) fn offset(mut self, offset: u32) -> Self {
231        self.intent = self.intent.offset(offset);
232        self
233    }
234
235    pub(in crate::db) fn build_plan(&self) -> Result<AccessPlannedQuery, QueryError> {
236        self.intent.build_plan_model()
237    }
238
239    pub(in crate::db) fn build_plan_with_visible_indexes(
240        &self,
241        visible_indexes: &VisibleIndexes<'_>,
242    ) -> Result<AccessPlannedQuery, QueryError> {
243        self.intent.build_plan_model_with_indexes(visible_indexes)
244    }
245
246    pub(in crate::db) fn prepare_normalized_scalar_predicate(
247        &self,
248    ) -> Result<Option<Predicate>, QueryError> {
249        self.intent.prepare_normalized_scalar_predicate()
250    }
251
252    pub(in crate::db) fn build_plan_with_visible_indexes_from_normalized_predicate(
253        &self,
254        visible_indexes: &VisibleIndexes<'_>,
255        normalized_predicate: Option<Predicate>,
256    ) -> Result<AccessPlannedQuery, QueryError> {
257        self.intent
258            .build_plan_model_with_indexes_from_normalized_predicate(
259                visible_indexes,
260                normalized_predicate,
261            )
262    }
263
264    #[must_use]
265    #[cfg(test)]
266    pub(in crate::db) fn structural_cache_key(
267        &self,
268    ) -> crate::db::query::intent::StructuralQueryCacheKey {
269        self.intent.structural_cache_key()
270    }
271
272    #[must_use]
273    pub(in crate::db) fn structural_cache_key_with_normalized_predicate(
274        &self,
275        predicate: Option<&Predicate>,
276    ) -> crate::db::query::intent::StructuralQueryCacheKey {
277        self.intent
278            .structural_cache_key_with_normalized_predicate(predicate)
279    }
280
281    // Build one access plan using either schema-owned indexes or the session
282    // visibility slice already resolved at the caller boundary.
283    fn build_plan_for_visibility(
284        &self,
285        visible_indexes: Option<&VisibleIndexes<'_>>,
286    ) -> Result<AccessPlannedQuery, QueryError> {
287        match visible_indexes {
288            Some(visible_indexes) => self.build_plan_with_visible_indexes(visible_indexes),
289            None => self.build_plan(),
290        }
291    }
292
293    // Assemble one canonical execution descriptor from a previously built
294    // access plan so text/json/verbose explain surfaces do not each rebuild it.
295    fn explain_execution_descriptor_from_plan(
296        &self,
297        plan: &AccessPlannedQuery,
298    ) -> Result<ExplainExecutionNodeDescriptor, QueryError> {
299        assemble_load_execution_node_descriptor(
300            self.intent.model().fields(),
301            self.intent.model().primary_key().name(),
302            plan,
303        )
304        .map_err(QueryError::execute)
305    }
306
307    // Render one verbose execution explain payload from a single access plan.
308    fn explain_execution_verbose_from_plan(
309        &self,
310        plan: &AccessPlannedQuery,
311    ) -> Result<String, QueryError> {
312        let descriptor = self.explain_execution_descriptor_from_plan(plan)?;
313        let route_diagnostics = assemble_load_execution_verbose_diagnostics(
314            self.intent.model().fields(),
315            self.intent.model().primary_key().name(),
316            plan,
317        )
318        .map_err(QueryError::execute)?;
319        let explain = plan.explain_with_model(self.intent.model());
320
321        // Phase 1: render descriptor tree with node-local metadata.
322        let mut lines = vec![descriptor.render_text_tree_verbose()];
323        lines.extend(route_diagnostics);
324
325        // Phase 2: add descriptor-stage summaries for key execution operators.
326        lines.push(format!(
327            "diag.d.has_top_n_seek={}",
328            contains_execution_node_type(&descriptor, ExplainExecutionNodeType::TopNSeek)
329        ));
330        lines.push(format!(
331            "diag.d.has_index_range_limit_pushdown={}",
332            contains_execution_node_type(
333                &descriptor,
334                ExplainExecutionNodeType::IndexRangeLimitPushdown,
335            )
336        ));
337        lines.push(format!(
338            "diag.d.has_index_predicate_prefilter={}",
339            contains_execution_node_type(
340                &descriptor,
341                ExplainExecutionNodeType::IndexPredicatePrefilter,
342            )
343        ));
344        lines.push(format!(
345            "diag.d.has_residual_predicate_filter={}",
346            contains_execution_node_type(
347                &descriptor,
348                ExplainExecutionNodeType::ResidualPredicateFilter,
349            )
350        ));
351
352        // Phase 3: append logical-plan diagnostics relevant to verbose explain.
353        lines.push(format!("diag.p.mode={:?}", explain.mode()));
354        lines.push(format!(
355            "diag.p.order_pushdown={}",
356            plan_order_pushdown_label(explain.order_pushdown())
357        ));
358        lines.push(format!(
359            "diag.p.predicate_pushdown={}",
360            plan_predicate_pushdown_label(explain.predicate(), explain.access())
361        ));
362        lines.push(format!("diag.p.distinct={}", explain.distinct()));
363        lines.push(format!("diag.p.page={:?}", explain.page()));
364        lines.push(format!("diag.p.consistency={:?}", explain.consistency()));
365
366        Ok(lines.join("\n"))
367    }
368
369    // Freeze one explain-only access-choice snapshot from the effective
370    // planner-visible index slice before building descriptor diagnostics.
371    fn finalize_explain_access_choice_for_visibility(
372        &self,
373        plan: &mut AccessPlannedQuery,
374        visible_indexes: Option<&VisibleIndexes<'_>>,
375    ) {
376        let visible_indexes = match visible_indexes {
377            Some(visible_indexes) => visible_indexes.as_slice(),
378            None => self.intent.model().indexes(),
379        };
380
381        plan.finalize_access_choice_for_model_with_indexes(self.intent.model(), visible_indexes);
382    }
383
384    // Build one execution descriptor after resolving the caller-visible index
385    // slice so text/json explain surfaces do not each duplicate plan assembly.
386    fn explain_execution_descriptor_for_visibility(
387        &self,
388        visible_indexes: Option<&VisibleIndexes<'_>>,
389    ) -> Result<ExplainExecutionNodeDescriptor, QueryError> {
390        let mut plan = self.build_plan_for_visibility(visible_indexes)?;
391        self.finalize_explain_access_choice_for_visibility(&mut plan, visible_indexes);
392
393        self.explain_execution_descriptor_from_plan(&plan)
394    }
395
396    // Render one verbose execution payload after resolving the caller-visible
397    // index slice exactly once at the structural query boundary.
398    fn explain_execution_verbose_for_visibility(
399        &self,
400        visible_indexes: Option<&VisibleIndexes<'_>>,
401    ) -> Result<String, QueryError> {
402        let mut plan = self.build_plan_for_visibility(visible_indexes)?;
403        self.finalize_explain_access_choice_for_visibility(&mut plan, visible_indexes);
404
405        self.explain_execution_verbose_from_plan(&plan)
406    }
407
408    #[cfg(feature = "sql")]
409    #[must_use]
410    pub(in crate::db) const fn model(&self) -> &'static crate::model::entity::EntityModel {
411        self.intent.model()
412    }
413
414    #[inline(never)]
415    pub(in crate::db) fn explain_execution_with_visible_indexes(
416        &self,
417        visible_indexes: &VisibleIndexes<'_>,
418    ) -> Result<ExplainExecutionNodeDescriptor, QueryError> {
419        self.explain_execution_descriptor_for_visibility(Some(visible_indexes))
420    }
421
422    // Explain one load execution shape through the structural query core.
423    #[inline(never)]
424    pub(in crate::db) fn explain_execution(
425        &self,
426    ) -> Result<ExplainExecutionNodeDescriptor, QueryError> {
427        self.explain_execution_descriptor_for_visibility(None)
428    }
429
430    // Render one verbose scalar load execution payload through the shared
431    // structural descriptor and route-diagnostics paths.
432    #[inline(never)]
433    pub(in crate::db) fn explain_execution_verbose(&self) -> Result<String, QueryError> {
434        self.explain_execution_verbose_for_visibility(None)
435    }
436
437    #[inline(never)]
438    pub(in crate::db) fn explain_execution_verbose_with_visible_indexes(
439        &self,
440        visible_indexes: &VisibleIndexes<'_>,
441    ) -> Result<String, QueryError> {
442        self.explain_execution_verbose_for_visibility(Some(visible_indexes))
443    }
444
445    #[inline(never)]
446    pub(in crate::db) fn explain_aggregate_terminal_with_visible_indexes(
447        &self,
448        visible_indexes: &VisibleIndexes<'_>,
449        aggregate: AggregateRouteShape<'_>,
450    ) -> Result<ExplainAggregateTerminalPlan, QueryError> {
451        let plan = self.build_plan_with_visible_indexes(visible_indexes)?;
452        let query_explain = plan.explain_with_model(self.intent.model());
453        let terminal = aggregate.kind();
454        let execution = assemble_aggregate_terminal_execution_descriptor(&plan, aggregate);
455
456        Ok(ExplainAggregateTerminalPlan::new(
457            query_explain,
458            terminal,
459            execution,
460        ))
461    }
462
463    #[inline(never)]
464    pub(in crate::db) fn explain_prepared_aggregate_terminal_with_visible_indexes<S>(
465        &self,
466        visible_indexes: &VisibleIndexes<'_>,
467        strategy: &S,
468    ) -> Result<ExplainAggregateTerminalPlan, QueryError>
469    where
470        S: PreparedFluentAggregateExplainStrategy,
471    {
472        let Some(kind) = strategy.explain_aggregate_kind() else {
473            return Err(QueryError::invariant(
474                "prepared fluent aggregate explain requires an explain-visible aggregate kind",
475            ));
476        };
477        let aggregate = AggregateRouteShape::new_from_fields(
478            kind,
479            strategy.explain_projected_field(),
480            self.intent.model().fields(),
481            self.intent.model().primary_key().name(),
482        );
483
484        self.explain_aggregate_terminal_with_visible_indexes(visible_indexes, aggregate)
485    }
486}
487
488///
489/// PlannedQueryCore
490///
491/// Generic-free planned-query payload shared by typed planned-query wrappers
492/// so explain and plan-hash logic stay structural while public callers retain
493/// entity-specific type inference.
494///
495
496#[derive(Debug)]
497struct PlannedQueryCore {
498    model: &'static crate::model::entity::EntityModel,
499    plan: AccessPlannedQuery,
500}
501
502impl PlannedQueryCore {
503    #[must_use]
504    const fn new(
505        model: &'static crate::model::entity::EntityModel,
506        plan: AccessPlannedQuery,
507    ) -> Self {
508        Self { model, plan }
509    }
510
511    #[must_use]
512    fn explain(&self) -> ExplainPlan {
513        self.plan.explain_with_model(self.model)
514    }
515
516    /// Return the stable plan hash for this planned query.
517    #[must_use]
518    fn plan_hash_hex(&self) -> String {
519        self.plan.fingerprint().to_string()
520    }
521}
522
523///
524/// PlannedQuery
525///
526/// Typed planned-query shell over one generic-free planner contract.
527/// This preserves caller-side entity inference while keeping the stored plan
528/// payload and explain/hash logic structural.
529///
530
531#[derive(Debug)]
532pub struct PlannedQuery<E: EntityKind> {
533    inner: PlannedQueryCore,
534    _marker: PhantomData<E>,
535}
536
537impl<E: EntityKind> PlannedQuery<E> {
538    #[must_use]
539    const fn from_inner(inner: PlannedQueryCore) -> Self {
540        Self {
541            inner,
542            _marker: PhantomData,
543        }
544    }
545
546    #[must_use]
547    pub fn explain(&self) -> ExplainPlan {
548        self.inner.explain()
549    }
550
551    /// Return the stable plan hash for this planned query.
552    #[must_use]
553    pub fn plan_hash_hex(&self) -> String {
554        self.inner.plan_hash_hex()
555    }
556}
557
558///
559/// CompiledQueryCore
560///
561/// Generic-free compiled-query payload shared by typed compiled-query wrappers
562/// so executor handoff state remains structural until the final typed adapter
563/// boundary.
564///
565
566#[derive(Clone, Debug)]
567struct CompiledQueryCore {
568    model: &'static crate::model::entity::EntityModel,
569    entity_path: &'static str,
570    plan: AccessPlannedQuery,
571}
572
573impl CompiledQueryCore {
574    #[must_use]
575    const fn new(
576        model: &'static crate::model::entity::EntityModel,
577        entity_path: &'static str,
578        plan: AccessPlannedQuery,
579    ) -> Self {
580        Self {
581            model,
582            entity_path,
583            plan,
584        }
585    }
586
587    #[must_use]
588    fn explain(&self) -> ExplainPlan {
589        self.plan.explain_with_model(self.model)
590    }
591
592    /// Return the stable plan hash for this compiled query.
593    #[must_use]
594    fn plan_hash_hex(&self) -> String {
595        self.plan.fingerprint().to_string()
596    }
597
598    #[must_use]
599    #[cfg(test)]
600    fn projection_spec(&self) -> crate::db::query::plan::expr::ProjectionSpec {
601        self.plan.projection_spec(self.model)
602    }
603
604    #[must_use]
605    fn into_inner(self) -> AccessPlannedQuery {
606        self.plan
607    }
608}
609
610///
611/// CompiledQuery
612///
613/// Typed compiled-query shell over one generic-free planner contract.
614/// The outer entity marker restores inference for executor handoff sites
615/// while the stored execution payload remains structural.
616///
617
618#[derive(Clone, Debug)]
619pub struct CompiledQuery<E: EntityKind> {
620    inner: CompiledQueryCore,
621    _marker: PhantomData<E>,
622}
623
624impl<E: EntityKind> CompiledQuery<E> {
625    #[must_use]
626    const fn from_inner(inner: CompiledQueryCore) -> Self {
627        Self {
628            inner,
629            _marker: PhantomData,
630        }
631    }
632
633    #[must_use]
634    pub fn explain(&self) -> ExplainPlan {
635        self.inner.explain()
636    }
637
638    /// Return the stable plan hash for this compiled query.
639    #[must_use]
640    pub fn plan_hash_hex(&self) -> String {
641        self.inner.plan_hash_hex()
642    }
643
644    #[must_use]
645    #[cfg(test)]
646    pub(in crate::db) fn projection_spec(&self) -> crate::db::query::plan::expr::ProjectionSpec {
647        self.inner.projection_spec()
648    }
649
650    /// Convert one structural compiled query into one prepared executor plan.
651    pub(in crate::db) fn into_prepared_execution_plan(
652        self,
653    ) -> crate::db::executor::PreparedExecutionPlan<E> {
654        assert!(
655            self.inner.entity_path == E::PATH,
656            "compiled query entity mismatch: compiled for '{}', requested '{}'",
657            self.inner.entity_path,
658            E::PATH,
659        );
660
661        crate::db::executor::PreparedExecutionPlan::new(self.into_inner())
662    }
663
664    #[must_use]
665    pub(in crate::db) fn into_inner(self) -> AccessPlannedQuery {
666        self.inner.into_inner()
667    }
668}
669
670///
671/// Query
672///
673/// Typed, declarative query intent for a specific entity type.
674///
675/// This intent is:
676/// - schema-agnostic at construction
677/// - normalized and validated only during planning
678/// - free of access-path decisions
679///
680
681#[derive(Debug)]
682pub struct Query<E: EntityKind> {
683    inner: StructuralQuery,
684    _marker: PhantomData<E>,
685}
686
687impl<E: EntityKind> Query<E> {
688    // Rebind one structural query core to the typed `Query<E>` surface.
689    pub(in crate::db) const fn from_inner(inner: StructuralQuery) -> Self {
690        Self {
691            inner,
692            _marker: PhantomData,
693        }
694    }
695
696    /// Create a new intent with an explicit missing-row policy.
697    /// Ignore favors idempotency and may mask index/data divergence on deletes.
698    /// Use Error to surface missing rows during scan/delete execution.
699    #[must_use]
700    pub const fn new(consistency: MissingRowPolicy) -> Self {
701        Self::from_inner(StructuralQuery::new(E::MODEL, consistency))
702    }
703
704    /// Return the intent mode (load vs delete).
705    #[must_use]
706    pub const fn mode(&self) -> QueryMode {
707        self.inner.mode()
708    }
709
710    pub(in crate::db) fn explain_with_visible_indexes(
711        &self,
712        visible_indexes: &VisibleIndexes<'_>,
713    ) -> Result<ExplainPlan, QueryError> {
714        let plan = self.build_plan_for_visibility(Some(visible_indexes))?;
715
716        Ok(plan.explain_with_model(E::MODEL))
717    }
718
719    pub(in crate::db) fn plan_hash_hex_with_visible_indexes(
720        &self,
721        visible_indexes: &VisibleIndexes<'_>,
722    ) -> Result<String, QueryError> {
723        let plan = self.build_plan_for_visibility(Some(visible_indexes))?;
724
725        Ok(plan.fingerprint().to_string())
726    }
727
728    // Build one typed access plan using either schema-owned indexes or the
729    // visibility slice already resolved at the session boundary.
730    fn build_plan_for_visibility(
731        &self,
732        visible_indexes: Option<&VisibleIndexes<'_>>,
733    ) -> Result<AccessPlannedQuery, QueryError> {
734        self.inner.build_plan_for_visibility(visible_indexes)
735    }
736
737    // Build one structural plan for the requested visibility lane and then
738    // project it into one typed query-owned contract so planned vs compiled
739    // outputs do not each duplicate the same plan handoff shape.
740    fn map_plan_for_visibility<T>(
741        &self,
742        visible_indexes: Option<&VisibleIndexes<'_>>,
743        map: impl FnOnce(AccessPlannedQuery) -> T,
744    ) -> Result<T, QueryError> {
745        let plan = self.build_plan_for_visibility(visible_indexes)?;
746
747        Ok(map(plan))
748    }
749
750    // Wrap one built plan as the typed planned-query DTO.
751    pub(in crate::db) fn planned_query_from_plan(plan: AccessPlannedQuery) -> PlannedQuery<E> {
752        let _projection = plan.projection_spec(E::MODEL);
753
754        PlannedQuery::from_inner(PlannedQueryCore::new(E::MODEL, plan))
755    }
756
757    // Wrap one built plan as the typed compiled-query DTO.
758    pub(in crate::db) fn compiled_query_from_plan(plan: AccessPlannedQuery) -> CompiledQuery<E> {
759        let _projection = plan.projection_spec(E::MODEL);
760
761        CompiledQuery::from_inner(CompiledQueryCore::new(E::MODEL, E::PATH, plan))
762    }
763
764    #[must_use]
765    pub(crate) fn has_explicit_order(&self) -> bool {
766        self.inner.has_explicit_order()
767    }
768
769    #[must_use]
770    pub(in crate::db) const fn structural(&self) -> &StructuralQuery {
771        &self.inner
772    }
773
774    #[must_use]
775    pub const fn has_grouping(&self) -> bool {
776        self.inner.has_grouping()
777    }
778
779    #[must_use]
780    pub(crate) const fn load_spec(&self) -> Option<LoadSpec> {
781        self.inner.load_spec()
782    }
783
784    /// Add a predicate, implicitly AND-ing with any existing predicate.
785    #[must_use]
786    pub fn filter(mut self, predicate: Predicate) -> Self {
787        self.inner = self.inner.filter(predicate);
788        self
789    }
790
791    /// Apply a dynamic filter expression.
792    pub fn filter_expr(self, expr: FilterExpr) -> Result<Self, QueryError> {
793        let Self { inner, .. } = self;
794        let inner = inner.filter_expr(expr)?;
795
796        Ok(Self::from_inner(inner))
797    }
798
799    /// Apply a dynamic sort expression.
800    pub fn sort_expr(self, expr: SortExpr) -> Result<Self, QueryError> {
801        let Self { inner, .. } = self;
802        let inner = inner.sort_expr(expr)?;
803
804        Ok(Self::from_inner(inner))
805    }
806
807    /// Append an ascending sort key.
808    #[must_use]
809    pub fn order_by(mut self, field: impl AsRef<str>) -> Self {
810        self.inner = self.inner.order_by(field);
811        self
812    }
813
814    /// Append a descending sort key.
815    #[must_use]
816    pub fn order_by_desc(mut self, field: impl AsRef<str>) -> Self {
817        self.inner = self.inner.order_by_desc(field);
818        self
819    }
820
821    /// Enable DISTINCT semantics for this query.
822    #[must_use]
823    pub fn distinct(mut self) -> Self {
824        self.inner = self.inner.distinct();
825        self
826    }
827
828    // Keep the internal fluent SQL parity hook available for lowering tests
829    // without making generated SQL binding depend on the typed query shell.
830    #[cfg(all(test, feature = "sql"))]
831    #[must_use]
832    pub(in crate::db) fn select_fields<I, S>(mut self, fields: I) -> Self
833    where
834        I: IntoIterator<Item = S>,
835        S: Into<String>,
836    {
837        self.inner = self.inner.select_fields(fields);
838        self
839    }
840
841    /// Add one GROUP BY field.
842    pub fn group_by(self, field: impl AsRef<str>) -> Result<Self, QueryError> {
843        let Self { inner, .. } = self;
844        let inner = inner.group_by(field)?;
845
846        Ok(Self::from_inner(inner))
847    }
848
849    /// Add one aggregate terminal via composable aggregate expression.
850    #[must_use]
851    pub fn aggregate(mut self, aggregate: AggregateExpr) -> Self {
852        self.inner = self.inner.aggregate(aggregate);
853        self
854    }
855
856    /// Override grouped hard limits for grouped execution budget enforcement.
857    #[must_use]
858    pub fn grouped_limits(mut self, max_groups: u64, max_group_bytes: u64) -> Self {
859        self.inner = self.inner.grouped_limits(max_groups, max_group_bytes);
860        self
861    }
862
863    /// Add one grouped HAVING compare clause over one grouped key field.
864    pub fn having_group(
865        self,
866        field: impl AsRef<str>,
867        op: CompareOp,
868        value: Value,
869    ) -> Result<Self, QueryError> {
870        let Self { inner, .. } = self;
871        let inner = inner.having_group(field, op, value)?;
872
873        Ok(Self::from_inner(inner))
874    }
875
876    /// Add one grouped HAVING compare clause over one grouped aggregate output.
877    pub fn having_aggregate(
878        self,
879        aggregate_index: usize,
880        op: CompareOp,
881        value: Value,
882    ) -> Result<Self, QueryError> {
883        let Self { inner, .. } = self;
884        let inner = inner.having_aggregate(aggregate_index, op, value)?;
885
886        Ok(Self::from_inner(inner))
887    }
888
889    /// Set the access path to a single primary key lookup.
890    pub(crate) fn by_id(self, id: E::Key) -> Self {
891        let Self { inner, .. } = self;
892
893        Self::from_inner(inner.by_id(id.to_value()))
894    }
895
896    /// Set the access path to a primary key batch lookup.
897    pub(crate) fn by_ids<I>(self, ids: I) -> Self
898    where
899        I: IntoIterator<Item = E::Key>,
900    {
901        let Self { inner, .. } = self;
902
903        Self::from_inner(inner.by_ids(ids.into_iter().map(|id| id.to_value())))
904    }
905
906    /// Mark this intent as a delete query.
907    #[must_use]
908    pub fn delete(mut self) -> Self {
909        self.inner = self.inner.delete();
910        self
911    }
912
913    /// Apply a limit to the current mode.
914    ///
915    /// Load limits bound result size; delete limits bound mutation size.
916    /// For scalar load queries, any use of `limit` or `offset` requires an
917    /// explicit `order_by(...)` so pagination is deterministic.
918    /// GROUP BY queries use canonical grouped-key order by default.
919    #[must_use]
920    pub fn limit(mut self, limit: u32) -> Self {
921        self.inner = self.inner.limit(limit);
922        self
923    }
924
925    /// Apply an offset to the current mode.
926    ///
927    /// Scalar load pagination requires an explicit `order_by(...)`.
928    /// GROUP BY queries use canonical grouped-key order by default.
929    /// Delete mode applies this after ordering and predicate filtering.
930    #[must_use]
931    pub fn offset(mut self, offset: u32) -> Self {
932        self.inner = self.inner.offset(offset);
933        self
934    }
935
936    /// Explain this intent without executing it.
937    pub fn explain(&self) -> Result<ExplainPlan, QueryError> {
938        let plan = self.planned()?;
939
940        Ok(plan.explain())
941    }
942
943    /// Return a stable plan hash for this intent.
944    ///
945    /// The hash is derived from canonical planner contracts and is suitable
946    /// for diagnostics, explain diffing, and cache key construction.
947    pub fn plan_hash_hex(&self) -> Result<String, QueryError> {
948        let plan = self.inner.build_plan()?;
949
950        Ok(plan.fingerprint().to_string())
951    }
952
953    // Resolve the structural execution descriptor through either the default
954    // schema-owned visibility lane or one caller-provided visible-index slice.
955    fn explain_execution_descriptor_for_visibility(
956        &self,
957        visible_indexes: Option<&VisibleIndexes<'_>>,
958    ) -> Result<ExplainExecutionNodeDescriptor, QueryError>
959    where
960        E: EntityValue,
961    {
962        match visible_indexes {
963            Some(visible_indexes) => self
964                .inner
965                .explain_execution_with_visible_indexes(visible_indexes),
966            None => self.inner.explain_execution(),
967        }
968    }
969
970    // Render one descriptor-derived execution surface after resolving the
971    // visibility slice once at the typed query boundary.
972    fn render_execution_descriptor_for_visibility(
973        &self,
974        visible_indexes: Option<&VisibleIndexes<'_>>,
975        render: impl FnOnce(ExplainExecutionNodeDescriptor) -> String,
976    ) -> Result<String, QueryError>
977    where
978        E: EntityValue,
979    {
980        let descriptor = self.explain_execution_descriptor_for_visibility(visible_indexes)?;
981
982        Ok(render(descriptor))
983    }
984
985    // Render one verbose execution explain payload after choosing the
986    // appropriate structural visibility lane once.
987    fn explain_execution_verbose_for_visibility(
988        &self,
989        visible_indexes: Option<&VisibleIndexes<'_>>,
990    ) -> Result<String, QueryError>
991    where
992        E: EntityValue,
993    {
994        match visible_indexes {
995            Some(visible_indexes) => self
996                .inner
997                .explain_execution_verbose_with_visible_indexes(visible_indexes),
998            None => self.inner.explain_execution_verbose(),
999        }
1000    }
1001
1002    /// Explain executor-selected load execution shape without running it.
1003    pub fn explain_execution(&self) -> Result<ExplainExecutionNodeDescriptor, QueryError>
1004    where
1005        E: EntityValue,
1006    {
1007        self.explain_execution_descriptor_for_visibility(None)
1008    }
1009
1010    pub(in crate::db) fn explain_execution_with_visible_indexes(
1011        &self,
1012        visible_indexes: &VisibleIndexes<'_>,
1013    ) -> Result<ExplainExecutionNodeDescriptor, QueryError>
1014    where
1015        E: EntityValue,
1016    {
1017        self.explain_execution_descriptor_for_visibility(Some(visible_indexes))
1018    }
1019
1020    /// Explain executor-selected load execution shape as deterministic text.
1021    pub fn explain_execution_text(&self) -> Result<String, QueryError>
1022    where
1023        E: EntityValue,
1024    {
1025        self.render_execution_descriptor_for_visibility(None, |descriptor| {
1026            descriptor.render_text_tree()
1027        })
1028    }
1029
1030    /// Explain executor-selected load execution shape as canonical JSON.
1031    pub fn explain_execution_json(&self) -> Result<String, QueryError>
1032    where
1033        E: EntityValue,
1034    {
1035        self.render_execution_descriptor_for_visibility(None, |descriptor| {
1036            descriptor.render_json_canonical()
1037        })
1038    }
1039
1040    /// Explain executor-selected load execution shape with route diagnostics.
1041    #[inline(never)]
1042    pub fn explain_execution_verbose(&self) -> Result<String, QueryError>
1043    where
1044        E: EntityValue,
1045    {
1046        self.explain_execution_verbose_for_visibility(None)
1047    }
1048
1049    // Build one aggregate-terminal explain payload without executing the query.
1050    #[cfg(test)]
1051    #[inline(never)]
1052    pub(in crate::db) fn explain_aggregate_terminal(
1053        &self,
1054        aggregate: AggregateExpr,
1055    ) -> Result<ExplainAggregateTerminalPlan, QueryError>
1056    where
1057        E: EntityValue,
1058    {
1059        self.inner.explain_aggregate_terminal_with_visible_indexes(
1060            &VisibleIndexes::schema_owned(E::MODEL.indexes()),
1061            AggregateRouteShape::new_from_fields(
1062                aggregate.kind(),
1063                aggregate.target_field(),
1064                E::MODEL.fields(),
1065                E::MODEL.primary_key().name(),
1066            ),
1067        )
1068    }
1069
1070    pub(in crate::db) fn explain_execution_verbose_with_visible_indexes(
1071        &self,
1072        visible_indexes: &VisibleIndexes<'_>,
1073    ) -> Result<String, QueryError>
1074    where
1075        E: EntityValue,
1076    {
1077        self.explain_execution_verbose_for_visibility(Some(visible_indexes))
1078    }
1079
1080    pub(in crate::db) fn explain_prepared_aggregate_terminal_with_visible_indexes<S>(
1081        &self,
1082        visible_indexes: &VisibleIndexes<'_>,
1083        strategy: &S,
1084    ) -> Result<ExplainAggregateTerminalPlan, QueryError>
1085    where
1086        E: EntityValue,
1087        S: PreparedFluentAggregateExplainStrategy,
1088    {
1089        self.inner
1090            .explain_prepared_aggregate_terminal_with_visible_indexes(visible_indexes, strategy)
1091    }
1092
1093    pub(in crate::db) fn explain_bytes_by_with_visible_indexes(
1094        &self,
1095        visible_indexes: &VisibleIndexes<'_>,
1096        target_field: &str,
1097    ) -> Result<ExplainExecutionNodeDescriptor, QueryError>
1098    where
1099        E: EntityValue,
1100    {
1101        let executable = self
1102            .plan_with_visible_indexes(visible_indexes)?
1103            .into_prepared_execution_plan();
1104        let mut descriptor = executable
1105            .explain_load_execution_node_descriptor()
1106            .map_err(QueryError::execute)?;
1107        let projection_mode = executable.bytes_by_projection_mode(target_field);
1108        let projection_mode_label =
1109            PreparedExecutionPlan::<E>::bytes_by_projection_mode_label(projection_mode);
1110
1111        descriptor
1112            .node_properties
1113            .insert("terminal", Value::from("bytes_by"));
1114        descriptor
1115            .node_properties
1116            .insert("terminal_field", Value::from(target_field.to_string()));
1117        descriptor.node_properties.insert(
1118            "terminal_projection_mode",
1119            Value::from(projection_mode_label),
1120        );
1121        descriptor.node_properties.insert(
1122            "terminal_index_only",
1123            Value::from(matches!(
1124                projection_mode,
1125                BytesByProjectionMode::CoveringIndex | BytesByProjectionMode::CoveringConstant
1126            )),
1127        );
1128
1129        Ok(descriptor)
1130    }
1131
1132    pub(in crate::db) fn explain_prepared_projection_terminal_with_visible_indexes(
1133        &self,
1134        visible_indexes: &VisibleIndexes<'_>,
1135        strategy: &PreparedFluentProjectionStrategy,
1136    ) -> Result<ExplainExecutionNodeDescriptor, QueryError>
1137    where
1138        E: EntityValue,
1139    {
1140        let executable = self
1141            .plan_with_visible_indexes(visible_indexes)?
1142            .into_prepared_execution_plan();
1143        let mut descriptor = executable
1144            .explain_load_execution_node_descriptor()
1145            .map_err(QueryError::execute)?;
1146        let projection_descriptor = strategy.explain_descriptor();
1147
1148        descriptor.node_properties.insert(
1149            "terminal",
1150            Value::from(projection_descriptor.terminal_label()),
1151        );
1152        descriptor.node_properties.insert(
1153            "terminal_field",
1154            Value::from(projection_descriptor.field_label().to_string()),
1155        );
1156        descriptor.node_properties.insert(
1157            "terminal_output",
1158            Value::from(projection_descriptor.output_label()),
1159        );
1160
1161        Ok(descriptor)
1162    }
1163
1164    /// Plan this intent into a neutral planned query contract.
1165    pub fn planned(&self) -> Result<PlannedQuery<E>, QueryError> {
1166        self.map_plan_for_visibility(None, Self::planned_query_from_plan)
1167    }
1168
1169    /// Compile this intent into query-owned handoff state.
1170    ///
1171    /// This boundary intentionally does not expose executor runtime shape.
1172    pub fn plan(&self) -> Result<CompiledQuery<E>, QueryError> {
1173        self.map_plan_for_visibility(None, Self::compiled_query_from_plan)
1174    }
1175
1176    pub(in crate::db) fn plan_with_visible_indexes(
1177        &self,
1178        visible_indexes: &VisibleIndexes<'_>,
1179    ) -> Result<CompiledQuery<E>, QueryError> {
1180        self.map_plan_for_visibility(Some(visible_indexes), Self::compiled_query_from_plan)
1181    }
1182}
1183
1184fn contains_execution_node_type(
1185    descriptor: &ExplainExecutionNodeDescriptor,
1186    target: ExplainExecutionNodeType,
1187) -> bool {
1188    descriptor.node_type() == target
1189        || descriptor
1190            .children()
1191            .iter()
1192            .any(|child| contains_execution_node_type(child, target))
1193}
1194
1195fn plan_order_pushdown_label(order_pushdown: &ExplainOrderPushdown) -> String {
1196    match order_pushdown {
1197        ExplainOrderPushdown::MissingModelContext => "missing_model_context".to_string(),
1198        ExplainOrderPushdown::EligibleSecondaryIndex { index, prefix_len } => {
1199            format!("eligible(index={index},prefix_len={prefix_len})",)
1200        }
1201        ExplainOrderPushdown::Rejected(reason) => format!("rejected({reason:?})"),
1202    }
1203}
1204
1205fn plan_predicate_pushdown_label(
1206    predicate: &ExplainPredicate,
1207    access: &ExplainAccessPath,
1208) -> String {
1209    let access_label = match access {
1210        ExplainAccessPath::ByKey { .. } => "by_key",
1211        ExplainAccessPath::ByKeys { keys } if keys.is_empty() => "empty_access_contract",
1212        ExplainAccessPath::ByKeys { .. } => "by_keys",
1213        ExplainAccessPath::KeyRange { .. } => "key_range",
1214        ExplainAccessPath::IndexPrefix { .. } => "index_prefix",
1215        ExplainAccessPath::IndexMultiLookup { .. } => "index_multi_lookup",
1216        ExplainAccessPath::IndexRange { .. } => "index_range",
1217        ExplainAccessPath::FullScan => "full_scan",
1218        ExplainAccessPath::Union(_) => "union",
1219        ExplainAccessPath::Intersection(_) => "intersection",
1220    };
1221    if matches!(predicate, ExplainPredicate::None) {
1222        return "none".to_string();
1223    }
1224    if matches!(access, ExplainAccessPath::FullScan) {
1225        if explain_predicate_contains_non_strict_compare(predicate) {
1226            return "fallback(non_strict_compare_coercion)".to_string();
1227        }
1228        if explain_predicate_contains_empty_prefix_starts_with(predicate) {
1229            return "fallback(starts_with_empty_prefix)".to_string();
1230        }
1231        if explain_predicate_contains_is_null(predicate) {
1232            return "fallback(is_null_full_scan)".to_string();
1233        }
1234        if explain_predicate_contains_text_scan_operator(predicate) {
1235            return "fallback(text_operator_full_scan)".to_string();
1236        }
1237
1238        return format!("fallback({access_label})");
1239    }
1240
1241    format!("applied({access_label})")
1242}
1243
1244fn explain_predicate_contains_non_strict_compare(predicate: &ExplainPredicate) -> bool {
1245    match predicate {
1246        ExplainPredicate::Compare { coercion, .. }
1247        | ExplainPredicate::CompareFields { coercion, .. } => coercion.id != CoercionId::Strict,
1248        ExplainPredicate::And(children) | ExplainPredicate::Or(children) => children
1249            .iter()
1250            .any(explain_predicate_contains_non_strict_compare),
1251        ExplainPredicate::Not(inner) => explain_predicate_contains_non_strict_compare(inner),
1252        ExplainPredicate::None
1253        | ExplainPredicate::True
1254        | ExplainPredicate::False
1255        | ExplainPredicate::IsNull { .. }
1256        | ExplainPredicate::IsNotNull { .. }
1257        | ExplainPredicate::IsMissing { .. }
1258        | ExplainPredicate::IsEmpty { .. }
1259        | ExplainPredicate::IsNotEmpty { .. }
1260        | ExplainPredicate::TextContains { .. }
1261        | ExplainPredicate::TextContainsCi { .. } => false,
1262    }
1263}
1264
1265fn explain_predicate_contains_is_null(predicate: &ExplainPredicate) -> bool {
1266    match predicate {
1267        ExplainPredicate::IsNull { .. } => true,
1268        ExplainPredicate::And(children) | ExplainPredicate::Or(children) => {
1269            children.iter().any(explain_predicate_contains_is_null)
1270        }
1271        ExplainPredicate::Not(inner) => explain_predicate_contains_is_null(inner),
1272        ExplainPredicate::None
1273        | ExplainPredicate::True
1274        | ExplainPredicate::False
1275        | ExplainPredicate::Compare { .. }
1276        | ExplainPredicate::CompareFields { .. }
1277        | ExplainPredicate::IsNotNull { .. }
1278        | ExplainPredicate::IsMissing { .. }
1279        | ExplainPredicate::IsEmpty { .. }
1280        | ExplainPredicate::IsNotEmpty { .. }
1281        | ExplainPredicate::TextContains { .. }
1282        | ExplainPredicate::TextContainsCi { .. } => false,
1283    }
1284}
1285
1286fn explain_predicate_contains_empty_prefix_starts_with(predicate: &ExplainPredicate) -> bool {
1287    match predicate {
1288        ExplainPredicate::Compare {
1289            op: CompareOp::StartsWith,
1290            value: Value::Text(prefix),
1291            ..
1292        } => prefix.is_empty(),
1293        ExplainPredicate::And(children) | ExplainPredicate::Or(children) => children
1294            .iter()
1295            .any(explain_predicate_contains_empty_prefix_starts_with),
1296        ExplainPredicate::Not(inner) => explain_predicate_contains_empty_prefix_starts_with(inner),
1297        ExplainPredicate::None
1298        | ExplainPredicate::True
1299        | ExplainPredicate::False
1300        | ExplainPredicate::Compare { .. }
1301        | ExplainPredicate::CompareFields { .. }
1302        | ExplainPredicate::IsNull { .. }
1303        | ExplainPredicate::IsNotNull { .. }
1304        | ExplainPredicate::IsMissing { .. }
1305        | ExplainPredicate::IsEmpty { .. }
1306        | ExplainPredicate::IsNotEmpty { .. }
1307        | ExplainPredicate::TextContains { .. }
1308        | ExplainPredicate::TextContainsCi { .. } => false,
1309    }
1310}
1311
1312fn explain_predicate_contains_text_scan_operator(predicate: &ExplainPredicate) -> bool {
1313    match predicate {
1314        ExplainPredicate::Compare {
1315            op: CompareOp::EndsWith,
1316            ..
1317        }
1318        | ExplainPredicate::TextContains { .. }
1319        | ExplainPredicate::TextContainsCi { .. } => true,
1320        ExplainPredicate::And(children) | ExplainPredicate::Or(children) => children
1321            .iter()
1322            .any(explain_predicate_contains_text_scan_operator),
1323        ExplainPredicate::Not(inner) => explain_predicate_contains_text_scan_operator(inner),
1324        ExplainPredicate::Compare { .. }
1325        | ExplainPredicate::CompareFields { .. }
1326        | ExplainPredicate::None
1327        | ExplainPredicate::True
1328        | ExplainPredicate::False
1329        | ExplainPredicate::IsNull { .. }
1330        | ExplainPredicate::IsNotNull { .. }
1331        | ExplainPredicate::IsMissing { .. }
1332        | ExplainPredicate::IsEmpty { .. }
1333        | ExplainPredicate::IsNotEmpty { .. } => false,
1334    }
1335}
1336
1337impl<E> Query<E>
1338where
1339    E: EntityKind + SingletonEntity,
1340    E::Key: Default,
1341{
1342    /// Set the access path to the singleton primary key.
1343    pub(crate) fn only(self) -> Self {
1344        let Self { inner, .. } = self;
1345
1346        Self::from_inner(inner.only(E::Key::default().to_value()))
1347    }
1348}