Skip to main content

icydb_core/db/query/intent/
query.rs

1use crate::{
2    db::{
3        predicate::{CompareOp, MissingRowPolicy, Predicate},
4        query::{
5            builder::aggregate::AggregateExpr,
6            explain::ExplainPlan,
7            expr::{FilterExpr, SortExpr},
8            intent::{QueryError, access_plan_to_entity_keys, model::QueryModel},
9            plan::{AccessPlannedQuery, LoadSpec, QueryMode},
10        },
11    },
12    traits::{EntityKind, SingletonEntity},
13    value::Value,
14};
15
16///
17/// Query
18///
19/// Typed, declarative query intent for a specific entity type.
20///
21/// This intent is:
22/// - schema-agnostic at construction
23/// - normalized and validated only during planning
24/// - free of access-path decisions
25///
26
27#[derive(Debug)]
28pub struct Query<E: EntityKind> {
29    intent: QueryModel<'static, E::Key>,
30}
31
32impl<E: EntityKind> Query<E> {
33    /// Create a new intent with an explicit missing-row policy.
34    /// Ignore favors idempotency and may mask index/data divergence on deletes.
35    /// Use Error to surface missing rows during scan/delete execution.
36    #[must_use]
37    pub const fn new(consistency: MissingRowPolicy) -> Self {
38        Self {
39            intent: QueryModel::new(E::MODEL, consistency),
40        }
41    }
42
43    /// Return the intent mode (load vs delete).
44    #[must_use]
45    pub const fn mode(&self) -> QueryMode {
46        self.intent.mode()
47    }
48
49    #[must_use]
50    pub(crate) fn has_explicit_order(&self) -> bool {
51        self.intent.has_explicit_order()
52    }
53
54    #[must_use]
55    pub(crate) const fn has_grouping(&self) -> bool {
56        self.intent.has_grouping()
57    }
58
59    #[must_use]
60    pub(crate) const fn load_spec(&self) -> Option<LoadSpec> {
61        match self.intent.mode() {
62            QueryMode::Load(spec) => Some(spec),
63            QueryMode::Delete(_) => None,
64        }
65    }
66
67    /// Add a predicate, implicitly AND-ing with any existing predicate.
68    #[must_use]
69    pub fn filter(mut self, predicate: Predicate) -> Self {
70        self.intent = self.intent.filter(predicate);
71        self
72    }
73
74    /// Apply a dynamic filter expression.
75    pub fn filter_expr(self, expr: FilterExpr) -> Result<Self, QueryError> {
76        let Self { intent } = self;
77        let intent = intent.filter_expr(expr)?;
78
79        Ok(Self { intent })
80    }
81
82    /// Apply a dynamic sort expression.
83    pub fn sort_expr(self, expr: SortExpr) -> Result<Self, QueryError> {
84        let Self { intent } = self;
85        let intent = intent.sort_expr(expr)?;
86
87        Ok(Self { intent })
88    }
89
90    /// Append an ascending sort key.
91    #[must_use]
92    pub fn order_by(mut self, field: impl AsRef<str>) -> Self {
93        self.intent = self.intent.order_by(field);
94        self
95    }
96
97    /// Append a descending sort key.
98    #[must_use]
99    pub fn order_by_desc(mut self, field: impl AsRef<str>) -> Self {
100        self.intent = self.intent.order_by_desc(field);
101        self
102    }
103
104    /// Enable DISTINCT semantics for this query.
105    #[must_use]
106    pub fn distinct(mut self) -> Self {
107        self.intent = self.intent.distinct();
108        self
109    }
110
111    /// Add one GROUP BY field.
112    pub fn group_by(self, field: impl AsRef<str>) -> Result<Self, QueryError> {
113        let Self { intent } = self;
114        let intent = intent.push_group_field(field.as_ref())?;
115
116        Ok(Self { intent })
117    }
118
119    /// Add one aggregate terminal via composable aggregate expression.
120    #[must_use]
121    pub fn aggregate(mut self, aggregate: AggregateExpr) -> Self {
122        self.intent = self.intent.push_group_aggregate(aggregate);
123        self
124    }
125
126    /// Override grouped hard limits for grouped execution budget enforcement.
127    #[must_use]
128    pub fn grouped_limits(mut self, max_groups: u64, max_group_bytes: u64) -> Self {
129        self.intent = self.intent.grouped_limits(max_groups, max_group_bytes);
130        self
131    }
132
133    /// Add one grouped HAVING compare clause over one grouped key field.
134    pub fn having_group(
135        self,
136        field: impl AsRef<str>,
137        op: CompareOp,
138        value: Value,
139    ) -> Result<Self, QueryError> {
140        let field = field.as_ref().to_owned();
141        let Self { intent } = self;
142        let intent = intent.push_having_group_clause(&field, op, value)?;
143
144        Ok(Self { intent })
145    }
146
147    /// Add one grouped HAVING compare clause over one grouped aggregate output.
148    pub fn having_aggregate(
149        self,
150        aggregate_index: usize,
151        op: CompareOp,
152        value: Value,
153    ) -> Result<Self, QueryError> {
154        let Self { intent } = self;
155        let intent = intent.push_having_aggregate_clause(aggregate_index, op, value)?;
156
157        Ok(Self { intent })
158    }
159
160    /// Set the access path to a single primary key lookup.
161    pub(crate) fn by_id(self, id: E::Key) -> Self {
162        let Self { intent } = self;
163        Self {
164            intent: intent.by_id(id),
165        }
166    }
167
168    /// Set the access path to a primary key batch lookup.
169    pub(crate) fn by_ids<I>(self, ids: I) -> Self
170    where
171        I: IntoIterator<Item = E::Key>,
172    {
173        let Self { intent } = self;
174        Self {
175            intent: intent.by_ids(ids),
176        }
177    }
178
179    /// Mark this intent as a delete query.
180    #[must_use]
181    pub fn delete(mut self) -> Self {
182        self.intent = self.intent.delete();
183        self
184    }
185
186    /// Apply a limit to the current mode.
187    ///
188    /// Load limits bound result size; delete limits bound mutation size.
189    /// For scalar load queries, any use of `limit` or `offset` requires an
190    /// explicit `order_by(...)` so pagination is deterministic.
191    /// GROUP BY queries use canonical grouped-key order by default.
192    #[must_use]
193    pub fn limit(mut self, limit: u32) -> Self {
194        self.intent = self.intent.limit(limit);
195        self
196    }
197
198    /// Apply an offset to a load intent.
199    ///
200    /// Scalar pagination requires an explicit `order_by(...)`.
201    /// GROUP BY queries use canonical grouped-key order by default.
202    /// Delete intents reject `offset(...)` during planning.
203    #[must_use]
204    pub fn offset(mut self, offset: u32) -> Self {
205        self.intent = self.intent.offset(offset);
206        self
207    }
208
209    /// Explain this intent without executing it.
210    pub fn explain(&self) -> Result<ExplainPlan, QueryError> {
211        let plan = self.planned()?;
212
213        Ok(plan.explain())
214    }
215
216    /// Plan this intent into a neutral planned query contract.
217    pub fn planned(&self) -> Result<PlannedQuery<E>, QueryError> {
218        let plan = self.build_plan()?;
219        let _projection = plan.projection_spec(E::MODEL);
220
221        Ok(PlannedQuery::new(plan))
222    }
223
224    /// Compile this intent into query-owned handoff state.
225    ///
226    /// This boundary intentionally does not expose executor runtime shape.
227    pub fn plan(&self) -> Result<CompiledQuery<E>, QueryError> {
228        let plan = self.build_plan()?;
229        let _projection = plan.projection_spec(E::MODEL);
230
231        Ok(CompiledQuery::new(plan))
232    }
233
234    // Build a logical plan for the current intent.
235    fn build_plan(&self) -> Result<AccessPlannedQuery<E::Key>, QueryError> {
236        let plan_value = self.intent.build_plan_model()?;
237        let (logical, access) = plan_value.into_parts();
238        let access = access_plan_to_entity_keys::<E>(E::MODEL, access)?;
239        let plan = AccessPlannedQuery::from_parts(logical, access);
240
241        Ok(plan)
242    }
243}
244
245impl<E> Query<E>
246where
247    E: EntityKind + SingletonEntity,
248    E::Key: Default,
249{
250    /// Set the access path to the singleton primary key.
251    pub(crate) fn only(self) -> Self {
252        let Self { intent } = self;
253
254        Self {
255            intent: intent.only(E::Key::default()),
256        }
257    }
258}
259
260///
261/// PlannedQuery
262///
263/// Neutral query-owned planned contract produced by query planning.
264/// Stores logical + access shape without executor compilation state.
265///
266
267#[derive(Debug)]
268pub struct PlannedQuery<E: EntityKind> {
269    plan: AccessPlannedQuery<E::Key>,
270}
271
272impl<E: EntityKind> PlannedQuery<E> {
273    #[must_use]
274    pub(in crate::db) const fn new(plan: AccessPlannedQuery<E::Key>) -> Self {
275        Self { plan }
276    }
277
278    #[must_use]
279    pub fn explain(&self) -> ExplainPlan {
280        self.plan.explain_with_model(E::MODEL)
281    }
282}
283
284///
285/// CompiledQuery
286///
287/// Query-owned compiled handoff produced by `Query::plan()`.
288/// This type intentionally carries only logical/access query semantics.
289/// Executor runtime shape is derived explicitly at the executor boundary.
290///
291
292#[derive(Clone, Debug)]
293pub struct CompiledQuery<E: EntityKind> {
294    plan: AccessPlannedQuery<E::Key>,
295}
296
297impl<E: EntityKind> CompiledQuery<E> {
298    #[must_use]
299    pub(in crate::db) const fn new(plan: AccessPlannedQuery<E::Key>) -> Self {
300        Self { plan }
301    }
302
303    #[must_use]
304    pub fn explain(&self) -> ExplainPlan {
305        self.plan.explain_with_model(E::MODEL)
306    }
307
308    /// Borrow planner-lowered projection semantics for this compiled query.
309    #[must_use]
310    #[cfg(test)]
311    pub(crate) fn projection_spec(&self) -> crate::db::query::plan::expr::ProjectionSpec {
312        self.plan.projection_spec(E::MODEL)
313    }
314
315    #[must_use]
316    pub(in crate::db) fn into_inner(self) -> AccessPlannedQuery<E::Key> {
317        self.plan
318    }
319}