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};
52
53///
54/// LoweredSqlCommand
55///
56/// Generic-free SQL command shape after reduced SQL parsing and entity-route
57/// normalization.
58/// This keeps statement-shape lowering shared across entities before typed
59/// `Query<E>` binding happens at the execution boundary.
60///
61#[derive(Clone, Debug)]
62pub struct LoweredSqlCommand(pub(in crate::db::sql::lowering) LoweredSqlCommandInner);
63
64#[derive(Clone, Debug)]
65pub(in crate::db::sql::lowering) enum LoweredSqlCommandInner {
66    Query(LoweredSqlQuery),
67    Explain {
68        mode: SqlExplainMode,
69        query: LoweredSqlQuery,
70    },
71    ExplainGlobalAggregate {
72        mode: SqlExplainMode,
73        command: LoweredSqlGlobalAggregateCommand,
74    },
75    DescribeEntity,
76    ShowIndexesEntity,
77    ShowColumnsEntity,
78    ShowEntities,
79}
80
81///
82/// SqlCommand
83///
84/// Test-only typed SQL command shell over the shared lowered SQL surface.
85/// Runtime dispatch now consumes `LoweredSqlCommand` directly, but lowering
86/// tests still validate typed binding behavior on this local envelope.
87///
88#[cfg(test)]
89#[derive(Debug)]
90pub(crate) enum SqlCommand<E: EntityKind> {
91    Query(Query<E>),
92    Explain {
93        mode: SqlExplainMode,
94        query: Query<E>,
95    },
96    ExplainGlobalAggregate {
97        mode: SqlExplainMode,
98        command: SqlGlobalAggregateCommand<E>,
99    },
100    DescribeEntity,
101    ShowIndexesEntity,
102    ShowColumnsEntity,
103    ShowEntities,
104}
105
106impl LoweredSqlCommand {
107    #[must_use]
108    #[cfg_attr(not(any(test, feature = "perf-attribution")), allow(dead_code))]
109    pub(in crate::db) const fn query(&self) -> Option<&LoweredSqlQuery> {
110        match &self.0 {
111            LoweredSqlCommandInner::Query(query) => Some(query),
112            LoweredSqlCommandInner::Explain { .. }
113            | LoweredSqlCommandInner::ExplainGlobalAggregate { .. }
114            | LoweredSqlCommandInner::DescribeEntity
115            | LoweredSqlCommandInner::ShowIndexesEntity
116            | LoweredSqlCommandInner::ShowColumnsEntity
117            | LoweredSqlCommandInner::ShowEntities => None,
118        }
119    }
120
121    #[must_use]
122    pub(in crate::db) fn into_query(self) -> Option<LoweredSqlQuery> {
123        match self.0 {
124            LoweredSqlCommandInner::Query(query) => Some(query),
125            LoweredSqlCommandInner::Explain { .. }
126            | LoweredSqlCommandInner::ExplainGlobalAggregate { .. }
127            | LoweredSqlCommandInner::DescribeEntity
128            | LoweredSqlCommandInner::ShowIndexesEntity
129            | LoweredSqlCommandInner::ShowColumnsEntity
130            | LoweredSqlCommandInner::ShowEntities => None,
131        }
132    }
133
134    #[must_use]
135    pub(in crate::db) const fn explain_query(&self) -> Option<(SqlExplainMode, &LoweredSqlQuery)> {
136        match &self.0 {
137            LoweredSqlCommandInner::Explain { mode, query } => Some((*mode, query)),
138            LoweredSqlCommandInner::Query(_)
139            | LoweredSqlCommandInner::ExplainGlobalAggregate { .. }
140            | LoweredSqlCommandInner::DescribeEntity
141            | LoweredSqlCommandInner::ShowIndexesEntity
142            | LoweredSqlCommandInner::ShowColumnsEntity
143            | LoweredSqlCommandInner::ShowEntities => None,
144        }
145    }
146}
147
148///
149/// LoweredSqlQuery
150///
151/// Generic-free executable SQL query shape prepared before typed query binding.
152/// Select and delete lowering stay shared until the final `Query<E>` build.
153///
154#[derive(Clone, Debug)]
155pub(crate) enum LoweredSqlQuery {
156    Select(LoweredSelectShape),
157    Delete(LoweredBaseQueryShape),
158}
159
160impl LoweredSqlQuery {
161    // Report whether this lowered query carries grouped execution semantics.
162    pub(crate) const fn has_grouping(&self) -> bool {
163        match self {
164            Self::Select(select) => select.has_grouping(),
165            Self::Delete(_) => false,
166        }
167    }
168}
169
170///
171/// SqlLoweringError
172///
173/// SQL frontend lowering failures before planner validation/execution.
174///
175#[derive(Debug, ThisError)]
176pub(crate) enum SqlLoweringError {
177    #[error("{0}")]
178    Parse(#[from] crate::db::sql::parser::SqlParseError),
179
180    #[error("{0}")]
181    Query(Box<QueryError>),
182
183    #[error("SQL entity '{sql_entity}' does not match requested entity type '{expected_entity}'")]
184    EntityMismatch {
185        sql_entity: String,
186        expected_entity: &'static str,
187    },
188
189    #[error(
190        "unsupported SQL SELECT projection; supported forms are SELECT *, field lists, or grouped aggregate shapes"
191    )]
192    UnsupportedSelectProjection,
193
194    #[error("unsupported SQL SELECT DISTINCT")]
195    UnsupportedSelectDistinct,
196
197    #[error("unsupported SQL GROUP BY projection shape")]
198    UnsupportedSelectGroupBy,
199
200    #[error("unsupported SQL HAVING shape")]
201    UnsupportedSelectHaving,
202
203    #[error("ORDER BY alias '{alias}' does not resolve to a supported order target")]
204    UnsupportedOrderByAlias { alias: String },
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 unsupported SELECT DISTINCT SQL lowering error.
222    const fn unsupported_select_distinct() -> Self {
223        Self::UnsupportedSelectDistinct
224    }
225
226    /// Construct one unsupported SELECT GROUP BY shape SQL lowering error.
227    const fn unsupported_select_group_by() -> Self {
228        Self::UnsupportedSelectGroupBy
229    }
230
231    /// Construct one unsupported SELECT HAVING shape SQL lowering error.
232    const fn unsupported_select_having() -> Self {
233        Self::UnsupportedSelectHaving
234    }
235
236    /// Construct one unsupported ORDER BY alias SQL lowering error.
237    fn unsupported_order_by_alias(alias: impl Into<String>) -> Self {
238        Self::UnsupportedOrderByAlias {
239            alias: alias.into(),
240        }
241    }
242}
243
244impl From<QueryError> for SqlLoweringError {
245    fn from(value: QueryError) -> Self {
246        Self::Query(Box::new(value))
247    }
248}
249
250///
251/// PreparedSqlStatement
252///
253/// SQL statement envelope after entity-scope normalization and
254/// entity-match validation for one target entity descriptor.
255///
256/// This pre-lowering contract is entity-agnostic and reusable across
257/// dynamic SQL route branches before typed `Query<E>` binding.
258///
259#[derive(Clone, Debug)]
260pub(crate) struct PreparedSqlStatement {
261    pub(in crate::db::sql::lowering) statement: SqlStatement,
262}
263
264impl PreparedSqlStatement {
265    /// Consume one prepared SQL statement back into its normalized parsed form.
266    #[must_use]
267    pub(in crate::db) fn into_statement(self) -> SqlStatement {
268        self.statement
269    }
270}
271
272#[derive(Clone, Copy, Debug, Eq, PartialEq)]
273pub(crate) enum LoweredSqlLaneKind {
274    Query,
275    Explain,
276    Describe,
277    ShowIndexes,
278    ShowColumns,
279    ShowEntities,
280}
281
282/// Parse and lower one SQL statement into canonical query intent for `E`.
283#[cfg(test)]
284pub(crate) fn compile_sql_command<E: EntityKind>(
285    sql: &str,
286    consistency: MissingRowPolicy,
287) -> Result<SqlCommand<E>, SqlLoweringError> {
288    let statement = crate::db::sql::parser::parse_sql(sql)?;
289
290    compile_sql_command_from_statement::<E>(statement, consistency)
291}
292
293/// Lower one parsed SQL statement into canonical query intent for `E`.
294#[cfg(test)]
295pub(crate) fn compile_sql_command_from_statement<E: EntityKind>(
296    statement: SqlStatement,
297    consistency: MissingRowPolicy,
298) -> Result<SqlCommand<E>, SqlLoweringError> {
299    let prepared = prepare_sql_statement(statement, E::MODEL.name())?;
300
301    compile_sql_command_from_prepared_statement::<E>(prepared, consistency)
302}
303
304/// Lower one prepared SQL statement into canonical query intent for `E`.
305#[cfg(test)]
306pub(crate) fn compile_sql_command_from_prepared_statement<E: EntityKind>(
307    prepared: PreparedSqlStatement,
308    consistency: MissingRowPolicy,
309) -> Result<SqlCommand<E>, SqlLoweringError> {
310    let lowered = lower_sql_command_from_prepared_statement(prepared, E::MODEL.primary_key.name)?;
311
312    bind_lowered_sql_command::<E>(lowered, consistency)
313}
314
315pub(crate) const fn lowered_sql_command_lane(command: &LoweredSqlCommand) -> LoweredSqlLaneKind {
316    match command.0 {
317        LoweredSqlCommandInner::Query(_) => LoweredSqlLaneKind::Query,
318        LoweredSqlCommandInner::Explain { .. }
319        | LoweredSqlCommandInner::ExplainGlobalAggregate { .. } => LoweredSqlLaneKind::Explain,
320        LoweredSqlCommandInner::DescribeEntity => LoweredSqlLaneKind::Describe,
321        LoweredSqlCommandInner::ShowIndexesEntity => LoweredSqlLaneKind::ShowIndexes,
322        LoweredSqlCommandInner::ShowColumnsEntity => LoweredSqlLaneKind::ShowColumns,
323        LoweredSqlCommandInner::ShowEntities => LoweredSqlLaneKind::ShowEntities,
324    }
325}
326
327/// Bind one shared generic-free SQL command shape to the typed query surface.
328#[cfg(test)]
329pub(crate) fn bind_lowered_sql_command<E: EntityKind>(
330    lowered: LoweredSqlCommand,
331    consistency: MissingRowPolicy,
332) -> Result<SqlCommand<E>, SqlLoweringError> {
333    match lowered.0 {
334        LoweredSqlCommandInner::Query(query) => Ok(SqlCommand::Query(bind_lowered_sql_query::<E>(
335            query,
336            consistency,
337        )?)),
338        LoweredSqlCommandInner::Explain { mode, query } => Ok(SqlCommand::Explain {
339            mode,
340            query: bind_lowered_sql_query::<E>(query, consistency)?,
341        }),
342        LoweredSqlCommandInner::ExplainGlobalAggregate { mode, command } => {
343            Ok(SqlCommand::ExplainGlobalAggregate {
344                mode,
345                command: aggregate::bind_lowered_sql_global_aggregate_command::<E>(
346                    command,
347                    consistency,
348                )?,
349            })
350        }
351        LoweredSqlCommandInner::DescribeEntity => Ok(SqlCommand::DescribeEntity),
352        LoweredSqlCommandInner::ShowIndexesEntity => Ok(SqlCommand::ShowIndexesEntity),
353        LoweredSqlCommandInner::ShowColumnsEntity => Ok(SqlCommand::ShowColumnsEntity),
354        LoweredSqlCommandInner::ShowEntities => Ok(SqlCommand::ShowEntities),
355    }
356}