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