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