Skip to main content

icydb_core/db/sql/lowering/
mod.rs

1//! Module: db::sql::lowering
2//! Responsibility: reduced SQL statement lowering into canonical query intent.
3//! Does not own: SQL tokenization/parsing, planner validation policy, or executor semantics.
4//! Boundary: frontend-only translation from parsed SQL statement contracts to `Query<E>`.
5
6mod aggregate;
7mod normalize;
8mod prepare;
9mod select;
10
11///
12/// TESTS
13///
14
15#[cfg(test)]
16mod tests;
17
18use crate::db::{
19    query::intent::QueryError,
20    sql::parser::{SqlExplainMode, SqlStatement},
21};
22#[cfg(test)]
23use crate::{
24    db::{predicate::MissingRowPolicy, query::intent::Query},
25    traits::EntityKind,
26};
27use thiserror::Error as ThisError;
28
29pub(in crate::db::sql::lowering) use aggregate::LoweredSqlGlobalAggregateCommand;
30pub(in crate::db) use aggregate::compile_sql_global_aggregate_command_core_from_prepared;
31pub(in crate::db) use aggregate::is_sql_global_aggregate_statement;
32#[cfg(test)]
33pub(crate) use aggregate::{
34    PreparedSqlScalarAggregateDescriptorShape, PreparedSqlScalarAggregateDomain,
35    PreparedSqlScalarAggregateEmptySetBehavior, PreparedSqlScalarAggregateOrderingRequirement,
36    PreparedSqlScalarAggregateRowSource, SqlGlobalAggregateCommand,
37    TypedSqlGlobalAggregateTerminal, compile_sql_global_aggregate_command,
38};
39pub(crate) use aggregate::{
40    PreparedSqlScalarAggregateRuntimeDescriptor, PreparedSqlScalarAggregateStrategy,
41    SqlGlobalAggregateCommandCore, bind_lowered_sql_explain_global_aggregate_structural,
42};
43pub(crate) use prepare::{lower_sql_command_from_prepared_statement, prepare_sql_statement};
44pub(in crate::db::sql::lowering) use select::apply_lowered_base_query_shape;
45#[cfg(test)]
46pub(in crate::db) use select::apply_lowered_select_shape;
47pub(crate) use select::{LoweredBaseQueryShape, LoweredSelectShape};
48pub(in crate::db) use select::{
49    bind_lowered_sql_query, bind_lowered_sql_query_structural,
50    bind_lowered_sql_select_query_structural, canonicalize_sql_predicate_for_model,
51    canonicalize_strict_sql_literal_for_kind,
52};
53
54///
55/// LoweredSqlCommand
56///
57/// Generic-free SQL command shape after reduced SQL parsing and entity-route
58/// normalization.
59/// This keeps statement-shape lowering shared across entities before typed
60/// `Query<E>` binding happens at the execution boundary.
61///
62#[derive(Clone, Debug)]
63pub struct LoweredSqlCommand(pub(in crate::db::sql::lowering) LoweredSqlCommandInner);
64
65#[derive(Clone, Debug)]
66pub(in crate::db::sql::lowering) enum LoweredSqlCommandInner {
67    Query(LoweredSqlQuery),
68    Explain {
69        mode: SqlExplainMode,
70        query: LoweredSqlQuery,
71    },
72    ExplainGlobalAggregate {
73        mode: SqlExplainMode,
74        command: LoweredSqlGlobalAggregateCommand,
75    },
76    DescribeEntity,
77    ShowIndexesEntity,
78    ShowColumnsEntity,
79    ShowEntities,
80}
81
82///
83/// SqlCommand
84///
85/// Test-only typed SQL command shell over the shared lowered SQL surface.
86/// Runtime dispatch now consumes `LoweredSqlCommand` directly, but lowering
87/// tests still validate typed binding behavior on this local envelope.
88///
89#[cfg(test)]
90#[derive(Debug)]
91pub(crate) enum SqlCommand<E: EntityKind> {
92    Query(Query<E>),
93    Explain {
94        mode: SqlExplainMode,
95        query: Query<E>,
96    },
97    ExplainGlobalAggregate {
98        mode: SqlExplainMode,
99        command: SqlGlobalAggregateCommand<E>,
100    },
101    DescribeEntity,
102    ShowIndexesEntity,
103    ShowColumnsEntity,
104    ShowEntities,
105}
106
107impl LoweredSqlCommand {
108    #[must_use]
109    #[cfg_attr(not(any(test, feature = "diagnostics")), allow(dead_code))]
110    pub(in crate::db) const fn query(&self) -> Option<&LoweredSqlQuery> {
111        match &self.0 {
112            LoweredSqlCommandInner::Query(query) => Some(query),
113            LoweredSqlCommandInner::Explain { .. }
114            | LoweredSqlCommandInner::ExplainGlobalAggregate { .. }
115            | LoweredSqlCommandInner::DescribeEntity
116            | LoweredSqlCommandInner::ShowIndexesEntity
117            | LoweredSqlCommandInner::ShowColumnsEntity
118            | LoweredSqlCommandInner::ShowEntities => None,
119        }
120    }
121
122    #[must_use]
123    pub(in crate::db) fn into_query(self) -> Option<LoweredSqlQuery> {
124        match self.0 {
125            LoweredSqlCommandInner::Query(query) => Some(query),
126            LoweredSqlCommandInner::Explain { .. }
127            | LoweredSqlCommandInner::ExplainGlobalAggregate { .. }
128            | LoweredSqlCommandInner::DescribeEntity
129            | LoweredSqlCommandInner::ShowIndexesEntity
130            | LoweredSqlCommandInner::ShowColumnsEntity
131            | LoweredSqlCommandInner::ShowEntities => None,
132        }
133    }
134
135    #[must_use]
136    pub(in crate::db) const fn explain_query(&self) -> Option<(SqlExplainMode, &LoweredSqlQuery)> {
137        match &self.0 {
138            LoweredSqlCommandInner::Explain { mode, query } => Some((*mode, query)),
139            LoweredSqlCommandInner::Query(_)
140            | LoweredSqlCommandInner::ExplainGlobalAggregate { .. }
141            | LoweredSqlCommandInner::DescribeEntity
142            | LoweredSqlCommandInner::ShowIndexesEntity
143            | LoweredSqlCommandInner::ShowColumnsEntity
144            | LoweredSqlCommandInner::ShowEntities => None,
145        }
146    }
147}
148
149///
150/// LoweredSqlQuery
151///
152/// Generic-free executable SQL query shape prepared before typed query binding.
153/// Select and delete lowering stay shared until the final `Query<E>` build.
154///
155#[derive(Clone, Debug)]
156pub(crate) enum LoweredSqlQuery {
157    Select(LoweredSelectShape),
158    Delete(LoweredBaseQueryShape),
159}
160
161///
162/// SqlLoweringError
163///
164/// SQL frontend lowering failures before planner validation/execution.
165///
166#[derive(Debug, ThisError)]
167pub(crate) enum SqlLoweringError {
168    #[error("{0}")]
169    Parse(#[from] crate::db::sql::parser::SqlParseError),
170
171    #[error("{0}")]
172    Query(Box<QueryError>),
173
174    #[error("SQL entity '{sql_entity}' does not match requested entity type '{expected_entity}'")]
175    EntityMismatch {
176        sql_entity: String,
177        expected_entity: &'static str,
178    },
179
180    #[error(
181        "unsupported SQL SELECT projection; supported forms are SELECT *, field lists, global aggregate terminal lists, or grouped aggregate shapes"
182    )]
183    UnsupportedSelectProjection,
184
185    #[error("unsupported SQL SELECT DISTINCT")]
186    UnsupportedSelectDistinct,
187
188    #[error("unsupported SQL GROUP BY projection shape")]
189    UnsupportedSelectGroupBy,
190
191    #[error("unsupported SQL HAVING shape")]
192    UnsupportedSelectHaving,
193
194    #[error("aggregate input expressions are not executable in this release")]
195    UnsupportedAggregateInputExpressions,
196
197    #[error("unknown field '{field}'")]
198    UnknownField { field: String },
199
200    #[error("ORDER BY alias '{alias}' does not resolve to a supported order target")]
201    UnsupportedOrderByAlias { alias: String },
202
203    #[error("query-lane lowering reached a non query-compatible statement")]
204    UnexpectedQueryLaneStatement,
205}
206
207impl SqlLoweringError {
208    /// Construct one entity-mismatch SQL lowering error.
209    fn entity_mismatch(sql_entity: impl Into<String>, expected_entity: &'static str) -> Self {
210        Self::EntityMismatch {
211            sql_entity: sql_entity.into(),
212            expected_entity,
213        }
214    }
215
216    /// Construct one unsupported SELECT projection SQL lowering error.
217    const fn unsupported_select_projection() -> Self {
218        Self::UnsupportedSelectProjection
219    }
220
221    /// Construct one query-lane lowering misuse error.
222    pub(crate) const fn unexpected_query_lane_statement() -> Self {
223        Self::UnexpectedQueryLaneStatement
224    }
225
226    /// Construct one unsupported SELECT DISTINCT SQL lowering error.
227    const fn unsupported_select_distinct() -> Self {
228        Self::UnsupportedSelectDistinct
229    }
230
231    /// Construct one unsupported SELECT GROUP BY shape SQL lowering error.
232    const fn unsupported_select_group_by() -> Self {
233        Self::UnsupportedSelectGroupBy
234    }
235
236    /// Construct one unsupported SELECT HAVING shape SQL lowering error.
237    const fn unsupported_select_having() -> Self {
238        Self::UnsupportedSelectHaving
239    }
240
241    /// Construct one aggregate-input execution seam SQL lowering error.
242    const fn unsupported_aggregate_input_expressions() -> Self {
243        Self::UnsupportedAggregateInputExpressions
244    }
245
246    /// Construct one unknown-field SQL lowering error.
247    fn unknown_field(field: impl Into<String>) -> Self {
248        Self::UnknownField {
249            field: field.into(),
250        }
251    }
252
253    /// Construct one unsupported ORDER BY alias SQL lowering error.
254    fn unsupported_order_by_alias(alias: impl Into<String>) -> Self {
255        Self::UnsupportedOrderByAlias {
256            alias: alias.into(),
257        }
258    }
259}
260
261impl From<QueryError> for SqlLoweringError {
262    fn from(value: QueryError) -> Self {
263        Self::Query(Box::new(value))
264    }
265}
266
267///
268/// PreparedSqlStatement
269///
270/// SQL statement envelope after entity-scope normalization and
271/// entity-match validation for one target entity descriptor.
272///
273/// This pre-lowering contract is entity-agnostic and reusable across
274/// dynamic SQL route branches before typed `Query<E>` binding.
275///
276#[derive(Clone, Debug)]
277pub(crate) struct PreparedSqlStatement {
278    pub(in crate::db::sql::lowering) statement: SqlStatement,
279}
280
281impl PreparedSqlStatement {
282    /// Consume one prepared SQL statement back into its normalized parsed form.
283    #[must_use]
284    pub(in crate::db) fn into_statement(self) -> SqlStatement {
285        self.statement
286    }
287}
288
289#[derive(Clone, Copy, Debug, Eq, PartialEq)]
290pub(crate) enum LoweredSqlLaneKind {
291    Query,
292    Explain,
293    Describe,
294    ShowIndexes,
295    ShowColumns,
296    ShowEntities,
297}
298
299/// Parse and lower one SQL statement into canonical query intent for `E`.
300#[cfg(test)]
301pub(crate) fn compile_sql_command<E: EntityKind>(
302    sql: &str,
303    consistency: MissingRowPolicy,
304) -> Result<SqlCommand<E>, SqlLoweringError> {
305    let statement = crate::db::sql::parser::parse_sql(sql)?;
306    let prepared = prepare_sql_statement(statement, E::MODEL.name())?;
307    let lowered = lower_sql_command_from_prepared_statement(prepared, E::MODEL)?;
308
309    // Keep the test-only typed envelope local to the single public test entry
310    // point instead of preserving a private forwarding chain.
311    match lowered.0 {
312        LoweredSqlCommandInner::Query(query) => Ok(SqlCommand::Query(bind_lowered_sql_query::<E>(
313            query,
314            consistency,
315        )?)),
316        LoweredSqlCommandInner::Explain { mode, query } => Ok(SqlCommand::Explain {
317            mode,
318            query: bind_lowered_sql_query::<E>(query, consistency)?,
319        }),
320        LoweredSqlCommandInner::ExplainGlobalAggregate { mode, command } => {
321            Ok(SqlCommand::ExplainGlobalAggregate {
322                mode,
323                command: aggregate::bind_lowered_sql_global_aggregate_command::<E>(
324                    command,
325                    consistency,
326                )?,
327            })
328        }
329        LoweredSqlCommandInner::DescribeEntity => Ok(SqlCommand::DescribeEntity),
330        LoweredSqlCommandInner::ShowIndexesEntity => Ok(SqlCommand::ShowIndexesEntity),
331        LoweredSqlCommandInner::ShowColumnsEntity => Ok(SqlCommand::ShowColumnsEntity),
332        LoweredSqlCommandInner::ShowEntities => Ok(SqlCommand::ShowEntities),
333    }
334}
335
336pub(crate) const fn lowered_sql_command_lane(command: &LoweredSqlCommand) -> LoweredSqlLaneKind {
337    match command.0 {
338        LoweredSqlCommandInner::Query(_) => LoweredSqlLaneKind::Query,
339        LoweredSqlCommandInner::Explain { .. }
340        | LoweredSqlCommandInner::ExplainGlobalAggregate { .. } => LoweredSqlLaneKind::Explain,
341        LoweredSqlCommandInner::DescribeEntity => LoweredSqlLaneKind::Describe,
342        LoweredSqlCommandInner::ShowIndexesEntity => LoweredSqlLaneKind::ShowIndexes,
343        LoweredSqlCommandInner::ShowColumnsEntity => LoweredSqlLaneKind::ShowColumns,
344        LoweredSqlCommandInner::ShowEntities => LoweredSqlLaneKind::ShowEntities,
345    }
346}