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