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        crate::db::query::intent::StructuralQueryCacheKey::from_query_model(&self.intent)
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();
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();
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    plan: AccessPlannedQuery,
499}
500
501impl PlannedQueryCore {
502    #[must_use]
503    const fn new(plan: AccessPlannedQuery) -> Self {
504        Self { plan }
505    }
506
507    #[must_use]
508    fn explain(&self) -> ExplainPlan {
509        self.plan.explain()
510    }
511
512    /// Return the stable plan hash for this planned query.
513    #[must_use]
514    fn plan_hash_hex(&self) -> String {
515        self.plan.fingerprint().to_string()
516    }
517}
518
519///
520/// PlannedQuery
521///
522/// Typed planned-query shell over one generic-free planner contract.
523/// This preserves caller-side entity inference while keeping the stored plan
524/// payload and explain/hash logic structural.
525///
526
527#[derive(Debug)]
528pub struct PlannedQuery<E: EntityKind> {
529    inner: PlannedQueryCore,
530    _marker: PhantomData<E>,
531}
532
533impl<E: EntityKind> PlannedQuery<E> {
534    #[must_use]
535    const fn from_inner(inner: PlannedQueryCore) -> Self {
536        Self {
537            inner,
538            _marker: PhantomData,
539        }
540    }
541
542    #[must_use]
543    pub fn explain(&self) -> ExplainPlan {
544        self.inner.explain()
545    }
546
547    /// Return the stable plan hash for this planned query.
548    #[must_use]
549    pub fn plan_hash_hex(&self) -> String {
550        self.inner.plan_hash_hex()
551    }
552}
553
554///
555/// CompiledQueryCore
556///
557/// Generic-free compiled-query payload shared by typed compiled-query wrappers
558/// so executor handoff state remains structural until the final typed adapter
559/// boundary.
560///
561
562#[derive(Clone, Debug)]
563struct CompiledQueryCore {
564    entity_path: &'static str,
565    plan: AccessPlannedQuery,
566}
567
568impl CompiledQueryCore {
569    #[must_use]
570    const fn new(entity_path: &'static str, plan: AccessPlannedQuery) -> Self {
571        Self { entity_path, plan }
572    }
573
574    #[must_use]
575    fn explain(&self) -> ExplainPlan {
576        self.plan.explain()
577    }
578
579    /// Return the stable plan hash for this compiled query.
580    #[must_use]
581    fn plan_hash_hex(&self) -> String {
582        self.plan.fingerprint().to_string()
583    }
584
585    #[must_use]
586    fn into_inner(self) -> AccessPlannedQuery {
587        self.plan
588    }
589}
590
591///
592/// CompiledQuery
593///
594/// Typed compiled-query shell over one generic-free planner contract.
595/// The outer entity marker restores inference for executor handoff sites
596/// while the stored execution payload remains structural.
597///
598
599#[derive(Clone, Debug)]
600pub struct CompiledQuery<E: EntityKind> {
601    inner: CompiledQueryCore,
602    _marker: PhantomData<E>,
603}
604
605impl<E: EntityKind> CompiledQuery<E> {
606    #[must_use]
607    const fn from_inner(inner: CompiledQueryCore) -> Self {
608        Self {
609            inner,
610            _marker: PhantomData,
611        }
612    }
613
614    #[must_use]
615    pub fn explain(&self) -> ExplainPlan {
616        self.inner.explain()
617    }
618
619    /// Return the stable plan hash for this compiled query.
620    #[must_use]
621    pub fn plan_hash_hex(&self) -> String {
622        self.inner.plan_hash_hex()
623    }
624
625    #[must_use]
626    #[cfg(test)]
627    pub(in crate::db) fn projection_spec(&self) -> crate::db::query::plan::expr::ProjectionSpec {
628        self.inner.plan.projection_spec(E::MODEL)
629    }
630
631    /// Convert one structural compiled query into one prepared executor plan.
632    pub(in crate::db) fn into_prepared_execution_plan(
633        self,
634    ) -> crate::db::executor::PreparedExecutionPlan<E> {
635        assert!(
636            self.inner.entity_path == E::PATH,
637            "compiled query entity mismatch: compiled for '{}', requested '{}'",
638            self.inner.entity_path,
639            E::PATH,
640        );
641
642        crate::db::executor::PreparedExecutionPlan::new(self.into_inner())
643    }
644
645    #[must_use]
646    pub(in crate::db) fn into_inner(self) -> AccessPlannedQuery {
647        self.inner.into_inner()
648    }
649}
650
651///
652/// Query
653///
654/// Typed, declarative query intent for a specific entity type.
655///
656/// This intent is:
657/// - schema-agnostic at construction
658/// - normalized and validated only during planning
659/// - free of access-path decisions
660///
661
662#[derive(Debug)]
663pub struct Query<E: EntityKind> {
664    inner: StructuralQuery,
665    _marker: PhantomData<E>,
666}
667
668impl<E: EntityKind> Query<E> {
669    // Rebind one structural query core to the typed `Query<E>` surface.
670    pub(in crate::db) const fn from_inner(inner: StructuralQuery) -> Self {
671        Self {
672            inner,
673            _marker: PhantomData,
674        }
675    }
676
677    /// Create a new intent with an explicit missing-row policy.
678    /// Ignore favors idempotency and may mask index/data divergence on deletes.
679    /// Use Error to surface missing rows during scan/delete execution.
680    #[must_use]
681    pub const fn new(consistency: MissingRowPolicy) -> Self {
682        Self::from_inner(StructuralQuery::new(E::MODEL, consistency))
683    }
684
685    /// Return the intent mode (load vs delete).
686    #[must_use]
687    pub const fn mode(&self) -> QueryMode {
688        self.inner.mode()
689    }
690
691    pub(in crate::db) fn explain_with_visible_indexes(
692        &self,
693        visible_indexes: &VisibleIndexes<'_>,
694    ) -> Result<ExplainPlan, QueryError> {
695        let plan = self.build_plan_for_visibility(Some(visible_indexes))?;
696
697        Ok(plan.explain())
698    }
699
700    pub(in crate::db) fn plan_hash_hex_with_visible_indexes(
701        &self,
702        visible_indexes: &VisibleIndexes<'_>,
703    ) -> Result<String, QueryError> {
704        let plan = self.build_plan_for_visibility(Some(visible_indexes))?;
705
706        Ok(plan.fingerprint().to_string())
707    }
708
709    // Build one typed access plan using either schema-owned indexes or the
710    // visibility slice already resolved at the session boundary.
711    fn build_plan_for_visibility(
712        &self,
713        visible_indexes: Option<&VisibleIndexes<'_>>,
714    ) -> Result<AccessPlannedQuery, QueryError> {
715        self.inner.build_plan_for_visibility(visible_indexes)
716    }
717
718    // Build one structural plan for the requested visibility lane and then
719    // project it into one typed query-owned contract so planned vs compiled
720    // outputs do not each duplicate the same plan handoff shape.
721    fn map_plan_for_visibility<T>(
722        &self,
723        visible_indexes: Option<&VisibleIndexes<'_>>,
724        map: impl FnOnce(AccessPlannedQuery) -> T,
725    ) -> Result<T, QueryError> {
726        let plan = self.build_plan_for_visibility(visible_indexes)?;
727
728        Ok(map(plan))
729    }
730
731    // Wrap one built plan as the typed planned-query DTO.
732    pub(in crate::db) const fn planned_query_from_plan(
733        plan: AccessPlannedQuery,
734    ) -> PlannedQuery<E> {
735        PlannedQuery::from_inner(PlannedQueryCore::new(plan))
736    }
737
738    // Wrap one built plan as the typed compiled-query DTO.
739    pub(in crate::db) const fn compiled_query_from_plan(
740        plan: AccessPlannedQuery,
741    ) -> CompiledQuery<E> {
742        CompiledQuery::from_inner(CompiledQueryCore::new(E::PATH, plan))
743    }
744
745    #[must_use]
746    pub(crate) fn has_explicit_order(&self) -> bool {
747        self.inner.has_explicit_order()
748    }
749
750    #[must_use]
751    pub(in crate::db) const fn structural(&self) -> &StructuralQuery {
752        &self.inner
753    }
754
755    #[must_use]
756    pub const fn has_grouping(&self) -> bool {
757        self.inner.has_grouping()
758    }
759
760    #[must_use]
761    pub(crate) const fn load_spec(&self) -> Option<LoadSpec> {
762        self.inner.load_spec()
763    }
764
765    /// Add a predicate, implicitly AND-ing with any existing predicate.
766    #[must_use]
767    pub fn filter(mut self, predicate: Predicate) -> Self {
768        self.inner = self.inner.filter(predicate);
769        self
770    }
771
772    /// Apply a dynamic filter expression.
773    pub fn filter_expr(self, expr: FilterExpr) -> Result<Self, QueryError> {
774        let Self { inner, .. } = self;
775        let inner = inner.filter_expr(expr)?;
776
777        Ok(Self::from_inner(inner))
778    }
779
780    /// Apply a dynamic sort expression.
781    pub fn sort_expr(self, expr: SortExpr) -> Result<Self, QueryError> {
782        let Self { inner, .. } = self;
783        let inner = inner.sort_expr(expr)?;
784
785        Ok(Self::from_inner(inner))
786    }
787
788    /// Append an ascending sort key.
789    #[must_use]
790    pub fn order_by(mut self, field: impl AsRef<str>) -> Self {
791        self.inner = self.inner.order_by(field);
792        self
793    }
794
795    /// Append a descending sort key.
796    #[must_use]
797    pub fn order_by_desc(mut self, field: impl AsRef<str>) -> Self {
798        self.inner = self.inner.order_by_desc(field);
799        self
800    }
801
802    /// Enable DISTINCT semantics for this query.
803    #[must_use]
804    pub fn distinct(mut self) -> Self {
805        self.inner = self.inner.distinct();
806        self
807    }
808
809    // Keep the internal fluent SQL parity hook available for lowering tests
810    // without making generated SQL binding depend on the typed query shell.
811    #[cfg(all(test, feature = "sql"))]
812    #[must_use]
813    pub(in crate::db) fn select_fields<I, S>(mut self, fields: I) -> Self
814    where
815        I: IntoIterator<Item = S>,
816        S: Into<String>,
817    {
818        self.inner = self.inner.select_fields(fields);
819        self
820    }
821
822    /// Add one GROUP BY field.
823    pub fn group_by(self, field: impl AsRef<str>) -> Result<Self, QueryError> {
824        let Self { inner, .. } = self;
825        let inner = inner.group_by(field)?;
826
827        Ok(Self::from_inner(inner))
828    }
829
830    /// Add one aggregate terminal via composable aggregate expression.
831    #[must_use]
832    pub fn aggregate(mut self, aggregate: AggregateExpr) -> Self {
833        self.inner = self.inner.aggregate(aggregate);
834        self
835    }
836
837    /// Override grouped hard limits for grouped execution budget enforcement.
838    #[must_use]
839    pub fn grouped_limits(mut self, max_groups: u64, max_group_bytes: u64) -> Self {
840        self.inner = self.inner.grouped_limits(max_groups, max_group_bytes);
841        self
842    }
843
844    /// Add one grouped HAVING compare clause over one grouped key field.
845    pub fn having_group(
846        self,
847        field: impl AsRef<str>,
848        op: CompareOp,
849        value: Value,
850    ) -> Result<Self, QueryError> {
851        let Self { inner, .. } = self;
852        let inner = inner.having_group(field, op, value)?;
853
854        Ok(Self::from_inner(inner))
855    }
856
857    /// Add one grouped HAVING compare clause over one grouped aggregate output.
858    pub fn having_aggregate(
859        self,
860        aggregate_index: usize,
861        op: CompareOp,
862        value: Value,
863    ) -> Result<Self, QueryError> {
864        let Self { inner, .. } = self;
865        let inner = inner.having_aggregate(aggregate_index, op, value)?;
866
867        Ok(Self::from_inner(inner))
868    }
869
870    /// Set the access path to a single primary key lookup.
871    pub(crate) fn by_id(self, id: E::Key) -> Self {
872        let Self { inner, .. } = self;
873
874        Self::from_inner(inner.by_id(id.to_value()))
875    }
876
877    /// Set the access path to a primary key batch lookup.
878    pub(crate) fn by_ids<I>(self, ids: I) -> Self
879    where
880        I: IntoIterator<Item = E::Key>,
881    {
882        let Self { inner, .. } = self;
883
884        Self::from_inner(inner.by_ids(ids.into_iter().map(|id| id.to_value())))
885    }
886
887    /// Mark this intent as a delete query.
888    #[must_use]
889    pub fn delete(mut self) -> Self {
890        self.inner = self.inner.delete();
891        self
892    }
893
894    /// Apply a limit to the current mode.
895    ///
896    /// Load limits bound result size; delete limits bound mutation size.
897    /// For scalar load queries, any use of `limit` or `offset` requires an
898    /// explicit `order_by(...)` so pagination is deterministic.
899    /// GROUP BY queries use canonical grouped-key order by default.
900    #[must_use]
901    pub fn limit(mut self, limit: u32) -> Self {
902        self.inner = self.inner.limit(limit);
903        self
904    }
905
906    /// Apply an offset to the current mode.
907    ///
908    /// Scalar load pagination requires an explicit `order_by(...)`.
909    /// GROUP BY queries use canonical grouped-key order by default.
910    /// Delete mode applies this after ordering and predicate filtering.
911    #[must_use]
912    pub fn offset(mut self, offset: u32) -> Self {
913        self.inner = self.inner.offset(offset);
914        self
915    }
916
917    /// Explain this intent without executing it.
918    pub fn explain(&self) -> Result<ExplainPlan, QueryError> {
919        let plan = self.planned()?;
920
921        Ok(plan.explain())
922    }
923
924    /// Return a stable plan hash for this intent.
925    ///
926    /// The hash is derived from canonical planner contracts and is suitable
927    /// for diagnostics, explain diffing, and cache key construction.
928    pub fn plan_hash_hex(&self) -> Result<String, QueryError> {
929        let plan = self.inner.build_plan()?;
930
931        Ok(plan.fingerprint().to_string())
932    }
933
934    // Resolve the structural execution descriptor through either the default
935    // schema-owned visibility lane or one caller-provided visible-index slice.
936    fn explain_execution_descriptor_for_visibility(
937        &self,
938        visible_indexes: Option<&VisibleIndexes<'_>>,
939    ) -> Result<ExplainExecutionNodeDescriptor, QueryError>
940    where
941        E: EntityValue,
942    {
943        match visible_indexes {
944            Some(visible_indexes) => self
945                .inner
946                .explain_execution_with_visible_indexes(visible_indexes),
947            None => self.inner.explain_execution(),
948        }
949    }
950
951    // Render one descriptor-derived execution surface after resolving the
952    // visibility slice once at the typed query boundary.
953    fn render_execution_descriptor_for_visibility(
954        &self,
955        visible_indexes: Option<&VisibleIndexes<'_>>,
956        render: impl FnOnce(ExplainExecutionNodeDescriptor) -> String,
957    ) -> Result<String, QueryError>
958    where
959        E: EntityValue,
960    {
961        let descriptor = self.explain_execution_descriptor_for_visibility(visible_indexes)?;
962
963        Ok(render(descriptor))
964    }
965
966    // Render one verbose execution explain payload after choosing the
967    // appropriate structural visibility lane once.
968    fn explain_execution_verbose_for_visibility(
969        &self,
970        visible_indexes: Option<&VisibleIndexes<'_>>,
971    ) -> Result<String, QueryError>
972    where
973        E: EntityValue,
974    {
975        match visible_indexes {
976            Some(visible_indexes) => self
977                .inner
978                .explain_execution_verbose_with_visible_indexes(visible_indexes),
979            None => self.inner.explain_execution_verbose(),
980        }
981    }
982
983    /// Explain executor-selected load execution shape without running it.
984    pub fn explain_execution(&self) -> Result<ExplainExecutionNodeDescriptor, QueryError>
985    where
986        E: EntityValue,
987    {
988        self.explain_execution_descriptor_for_visibility(None)
989    }
990
991    pub(in crate::db) fn explain_execution_with_visible_indexes(
992        &self,
993        visible_indexes: &VisibleIndexes<'_>,
994    ) -> Result<ExplainExecutionNodeDescriptor, QueryError>
995    where
996        E: EntityValue,
997    {
998        self.explain_execution_descriptor_for_visibility(Some(visible_indexes))
999    }
1000
1001    /// Explain executor-selected load execution shape as deterministic text.
1002    pub fn explain_execution_text(&self) -> Result<String, QueryError>
1003    where
1004        E: EntityValue,
1005    {
1006        self.render_execution_descriptor_for_visibility(None, |descriptor| {
1007            descriptor.render_text_tree()
1008        })
1009    }
1010
1011    /// Explain executor-selected load execution shape as canonical JSON.
1012    pub fn explain_execution_json(&self) -> Result<String, QueryError>
1013    where
1014        E: EntityValue,
1015    {
1016        self.render_execution_descriptor_for_visibility(None, |descriptor| {
1017            descriptor.render_json_canonical()
1018        })
1019    }
1020
1021    /// Explain executor-selected load execution shape with route diagnostics.
1022    #[inline(never)]
1023    pub fn explain_execution_verbose(&self) -> Result<String, QueryError>
1024    where
1025        E: EntityValue,
1026    {
1027        self.explain_execution_verbose_for_visibility(None)
1028    }
1029
1030    pub(in crate::db) fn explain_execution_verbose_with_visible_indexes(
1031        &self,
1032        visible_indexes: &VisibleIndexes<'_>,
1033    ) -> Result<String, QueryError>
1034    where
1035        E: EntityValue,
1036    {
1037        self.explain_execution_verbose_for_visibility(Some(visible_indexes))
1038    }
1039
1040    // Build one aggregate-terminal explain payload without executing the query.
1041    #[cfg(test)]
1042    #[inline(never)]
1043    pub(in crate::db) fn explain_aggregate_terminal(
1044        &self,
1045        aggregate: AggregateExpr,
1046    ) -> Result<ExplainAggregateTerminalPlan, QueryError>
1047    where
1048        E: EntityValue,
1049    {
1050        self.inner.explain_aggregate_terminal_with_visible_indexes(
1051            &VisibleIndexes::schema_owned(E::MODEL.indexes()),
1052            AggregateRouteShape::new_from_fields(
1053                aggregate.kind(),
1054                aggregate.target_field(),
1055                E::MODEL.fields(),
1056                E::MODEL.primary_key().name(),
1057            ),
1058        )
1059    }
1060
1061    pub(in crate::db) fn explain_prepared_aggregate_terminal_with_visible_indexes<S>(
1062        &self,
1063        visible_indexes: &VisibleIndexes<'_>,
1064        strategy: &S,
1065    ) -> Result<ExplainAggregateTerminalPlan, QueryError>
1066    where
1067        E: EntityValue,
1068        S: PreparedFluentAggregateExplainStrategy,
1069    {
1070        self.inner
1071            .explain_prepared_aggregate_terminal_with_visible_indexes(visible_indexes, strategy)
1072    }
1073
1074    pub(in crate::db) fn explain_bytes_by_with_visible_indexes(
1075        &self,
1076        visible_indexes: &VisibleIndexes<'_>,
1077        target_field: &str,
1078    ) -> Result<ExplainExecutionNodeDescriptor, QueryError>
1079    where
1080        E: EntityValue,
1081    {
1082        let executable = self
1083            .plan_with_visible_indexes(visible_indexes)?
1084            .into_prepared_execution_plan();
1085        let mut descriptor = executable
1086            .explain_load_execution_node_descriptor()
1087            .map_err(QueryError::execute)?;
1088        let projection_mode = executable.bytes_by_projection_mode(target_field);
1089        let projection_mode_label =
1090            PreparedExecutionPlan::<E>::bytes_by_projection_mode_label(projection_mode);
1091
1092        descriptor
1093            .node_properties
1094            .insert("terminal", Value::from("bytes_by"));
1095        descriptor
1096            .node_properties
1097            .insert("terminal_field", Value::from(target_field.to_string()));
1098        descriptor.node_properties.insert(
1099            "terminal_projection_mode",
1100            Value::from(projection_mode_label),
1101        );
1102        descriptor.node_properties.insert(
1103            "terminal_index_only",
1104            Value::from(matches!(
1105                projection_mode,
1106                BytesByProjectionMode::CoveringIndex | BytesByProjectionMode::CoveringConstant
1107            )),
1108        );
1109
1110        Ok(descriptor)
1111    }
1112
1113    pub(in crate::db) fn explain_prepared_projection_terminal_with_visible_indexes(
1114        &self,
1115        visible_indexes: &VisibleIndexes<'_>,
1116        strategy: &PreparedFluentProjectionStrategy,
1117    ) -> Result<ExplainExecutionNodeDescriptor, QueryError>
1118    where
1119        E: EntityValue,
1120    {
1121        let executable = self
1122            .plan_with_visible_indexes(visible_indexes)?
1123            .into_prepared_execution_plan();
1124        let mut descriptor = executable
1125            .explain_load_execution_node_descriptor()
1126            .map_err(QueryError::execute)?;
1127        let projection_descriptor = strategy.explain_descriptor();
1128
1129        descriptor.node_properties.insert(
1130            "terminal",
1131            Value::from(projection_descriptor.terminal_label()),
1132        );
1133        descriptor.node_properties.insert(
1134            "terminal_field",
1135            Value::from(projection_descriptor.field_label().to_string()),
1136        );
1137        descriptor.node_properties.insert(
1138            "terminal_output",
1139            Value::from(projection_descriptor.output_label()),
1140        );
1141
1142        Ok(descriptor)
1143    }
1144
1145    /// Plan this intent into a neutral planned query contract.
1146    pub fn planned(&self) -> Result<PlannedQuery<E>, QueryError> {
1147        self.map_plan_for_visibility(None, Self::planned_query_from_plan)
1148    }
1149
1150    /// Compile this intent into query-owned handoff state.
1151    ///
1152    /// This boundary intentionally does not expose executor runtime shape.
1153    pub fn plan(&self) -> Result<CompiledQuery<E>, QueryError> {
1154        self.map_plan_for_visibility(None, Self::compiled_query_from_plan)
1155    }
1156
1157    pub(in crate::db) fn plan_with_visible_indexes(
1158        &self,
1159        visible_indexes: &VisibleIndexes<'_>,
1160    ) -> Result<CompiledQuery<E>, QueryError> {
1161        self.map_plan_for_visibility(Some(visible_indexes), Self::compiled_query_from_plan)
1162    }
1163}
1164
1165fn contains_execution_node_type(
1166    descriptor: &ExplainExecutionNodeDescriptor,
1167    target: ExplainExecutionNodeType,
1168) -> bool {
1169    descriptor.node_type() == target
1170        || descriptor
1171            .children()
1172            .iter()
1173            .any(|child| contains_execution_node_type(child, target))
1174}
1175
1176fn plan_order_pushdown_label(order_pushdown: &ExplainOrderPushdown) -> String {
1177    match order_pushdown {
1178        ExplainOrderPushdown::MissingModelContext => "missing_model_context".to_string(),
1179        ExplainOrderPushdown::EligibleSecondaryIndex { index, prefix_len } => {
1180            format!("eligible(index={index},prefix_len={prefix_len})",)
1181        }
1182        ExplainOrderPushdown::Rejected(reason) => format!("rejected({reason:?})"),
1183    }
1184}
1185
1186fn plan_predicate_pushdown_label(
1187    predicate: &ExplainPredicate,
1188    access: &ExplainAccessPath,
1189) -> String {
1190    let access_label = match access {
1191        ExplainAccessPath::ByKey { .. } => "by_key",
1192        ExplainAccessPath::ByKeys { keys } if keys.is_empty() => "empty_access_contract",
1193        ExplainAccessPath::ByKeys { .. } => "by_keys",
1194        ExplainAccessPath::KeyRange { .. } => "key_range",
1195        ExplainAccessPath::IndexPrefix { .. } => "index_prefix",
1196        ExplainAccessPath::IndexMultiLookup { .. } => "index_multi_lookup",
1197        ExplainAccessPath::IndexRange { .. } => "index_range",
1198        ExplainAccessPath::FullScan => "full_scan",
1199        ExplainAccessPath::Union(_) => "union",
1200        ExplainAccessPath::Intersection(_) => "intersection",
1201    };
1202    if matches!(predicate, ExplainPredicate::None) {
1203        return "none".to_string();
1204    }
1205    if matches!(access, ExplainAccessPath::FullScan) {
1206        if explain_predicate_contains_non_strict_compare(predicate) {
1207            return "fallback(non_strict_compare_coercion)".to_string();
1208        }
1209        if explain_predicate_contains_empty_prefix_starts_with(predicate) {
1210            return "fallback(starts_with_empty_prefix)".to_string();
1211        }
1212        if explain_predicate_contains_is_null(predicate) {
1213            return "fallback(is_null_full_scan)".to_string();
1214        }
1215        if explain_predicate_contains_text_scan_operator(predicate) {
1216            return "fallback(text_operator_full_scan)".to_string();
1217        }
1218
1219        return format!("fallback({access_label})");
1220    }
1221
1222    format!("applied({access_label})")
1223}
1224
1225fn explain_predicate_contains_non_strict_compare(predicate: &ExplainPredicate) -> bool {
1226    match predicate {
1227        ExplainPredicate::Compare { coercion, .. }
1228        | ExplainPredicate::CompareFields { coercion, .. } => coercion.id != CoercionId::Strict,
1229        ExplainPredicate::And(children) | ExplainPredicate::Or(children) => children
1230            .iter()
1231            .any(explain_predicate_contains_non_strict_compare),
1232        ExplainPredicate::Not(inner) => explain_predicate_contains_non_strict_compare(inner),
1233        ExplainPredicate::None
1234        | ExplainPredicate::True
1235        | ExplainPredicate::False
1236        | ExplainPredicate::IsNull { .. }
1237        | ExplainPredicate::IsNotNull { .. }
1238        | ExplainPredicate::IsMissing { .. }
1239        | ExplainPredicate::IsEmpty { .. }
1240        | ExplainPredicate::IsNotEmpty { .. }
1241        | ExplainPredicate::TextContains { .. }
1242        | ExplainPredicate::TextContainsCi { .. } => false,
1243    }
1244}
1245
1246fn explain_predicate_contains_is_null(predicate: &ExplainPredicate) -> bool {
1247    match predicate {
1248        ExplainPredicate::IsNull { .. } => true,
1249        ExplainPredicate::And(children) | ExplainPredicate::Or(children) => {
1250            children.iter().any(explain_predicate_contains_is_null)
1251        }
1252        ExplainPredicate::Not(inner) => explain_predicate_contains_is_null(inner),
1253        ExplainPredicate::None
1254        | ExplainPredicate::True
1255        | ExplainPredicate::False
1256        | ExplainPredicate::Compare { .. }
1257        | ExplainPredicate::CompareFields { .. }
1258        | ExplainPredicate::IsNotNull { .. }
1259        | ExplainPredicate::IsMissing { .. }
1260        | ExplainPredicate::IsEmpty { .. }
1261        | ExplainPredicate::IsNotEmpty { .. }
1262        | ExplainPredicate::TextContains { .. }
1263        | ExplainPredicate::TextContainsCi { .. } => false,
1264    }
1265}
1266
1267fn explain_predicate_contains_empty_prefix_starts_with(predicate: &ExplainPredicate) -> bool {
1268    match predicate {
1269        ExplainPredicate::Compare {
1270            op: CompareOp::StartsWith,
1271            value: Value::Text(prefix),
1272            ..
1273        } => prefix.is_empty(),
1274        ExplainPredicate::And(children) | ExplainPredicate::Or(children) => children
1275            .iter()
1276            .any(explain_predicate_contains_empty_prefix_starts_with),
1277        ExplainPredicate::Not(inner) => explain_predicate_contains_empty_prefix_starts_with(inner),
1278        ExplainPredicate::None
1279        | ExplainPredicate::True
1280        | ExplainPredicate::False
1281        | ExplainPredicate::Compare { .. }
1282        | ExplainPredicate::CompareFields { .. }
1283        | ExplainPredicate::IsNull { .. }
1284        | ExplainPredicate::IsNotNull { .. }
1285        | ExplainPredicate::IsMissing { .. }
1286        | ExplainPredicate::IsEmpty { .. }
1287        | ExplainPredicate::IsNotEmpty { .. }
1288        | ExplainPredicate::TextContains { .. }
1289        | ExplainPredicate::TextContainsCi { .. } => false,
1290    }
1291}
1292
1293fn explain_predicate_contains_text_scan_operator(predicate: &ExplainPredicate) -> bool {
1294    match predicate {
1295        ExplainPredicate::Compare {
1296            op: CompareOp::EndsWith,
1297            ..
1298        }
1299        | ExplainPredicate::TextContains { .. }
1300        | ExplainPredicate::TextContainsCi { .. } => true,
1301        ExplainPredicate::And(children) | ExplainPredicate::Or(children) => children
1302            .iter()
1303            .any(explain_predicate_contains_text_scan_operator),
1304        ExplainPredicate::Not(inner) => explain_predicate_contains_text_scan_operator(inner),
1305        ExplainPredicate::Compare { .. }
1306        | ExplainPredicate::CompareFields { .. }
1307        | ExplainPredicate::None
1308        | ExplainPredicate::True
1309        | ExplainPredicate::False
1310        | ExplainPredicate::IsNull { .. }
1311        | ExplainPredicate::IsNotNull { .. }
1312        | ExplainPredicate::IsMissing { .. }
1313        | ExplainPredicate::IsEmpty { .. }
1314        | ExplainPredicate::IsNotEmpty { .. } => false,
1315    }
1316}
1317
1318impl<E> Query<E>
1319where
1320    E: EntityKind + SingletonEntity,
1321    E::Key: Default,
1322{
1323    /// Set the access path to the singleton primary key.
1324    pub(crate) fn only(self) -> Self {
1325        let Self { inner, .. } = self;
1326
1327        Self::from_inner(inner.only(E::Key::default().to_value()))
1328    }
1329}