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
160///
161/// SqlLoweringError
162///
163/// SQL frontend lowering failures before planner validation/execution.
164///
165#[derive(Debug, ThisError)]
166pub(crate) enum SqlLoweringError {
167    #[error("{0}")]
168    Parse(#[from] crate::db::sql::parser::SqlParseError),
169
170    #[error("{0}")]
171    Query(Box<QueryError>),
172
173    #[error("SQL entity '{sql_entity}' does not match requested entity type '{expected_entity}'")]
174    EntityMismatch {
175        sql_entity: String,
176        expected_entity: &'static str,
177    },
178
179    #[error(
180        "unsupported SQL SELECT projection; supported forms are SELECT *, field lists, or grouped aggregate shapes"
181    )]
182    UnsupportedSelectProjection,
183
184    #[error("unsupported SQL SELECT DISTINCT")]
185    UnsupportedSelectDistinct,
186
187    #[error("unsupported SQL GROUP BY projection shape")]
188    UnsupportedSelectGroupBy,
189
190    #[error("unsupported SQL HAVING shape")]
191    UnsupportedSelectHaving,
192
193    #[error("ORDER BY alias '{alias}' does not resolve to a supported order target")]
194    UnsupportedOrderByAlias { alias: String },
195
196    #[error("query-lane lowering reached a non query-compatible statement")]
197    UnexpectedQueryLaneStatement,
198}
199
200impl SqlLoweringError {
201    /// Construct one entity-mismatch SQL lowering error.
202    fn entity_mismatch(sql_entity: impl Into<String>, expected_entity: &'static str) -> Self {
203        Self::EntityMismatch {
204            sql_entity: sql_entity.into(),
205            expected_entity,
206        }
207    }
208
209    /// Construct one unsupported SELECT projection SQL lowering error.
210    const fn unsupported_select_projection() -> Self {
211        Self::UnsupportedSelectProjection
212    }
213
214    /// Construct one query-lane lowering misuse error.
215    pub(crate) const fn unexpected_query_lane_statement() -> Self {
216        Self::UnexpectedQueryLaneStatement
217    }
218
219    /// Construct one unsupported SELECT DISTINCT SQL lowering error.
220    const fn unsupported_select_distinct() -> Self {
221        Self::UnsupportedSelectDistinct
222    }
223
224    /// Construct one unsupported SELECT GROUP BY shape SQL lowering error.
225    const fn unsupported_select_group_by() -> Self {
226        Self::UnsupportedSelectGroupBy
227    }
228
229    /// Construct one unsupported SELECT HAVING shape SQL lowering error.
230    const fn unsupported_select_having() -> Self {
231        Self::UnsupportedSelectHaving
232    }
233
234    /// Construct one unsupported ORDER BY alias SQL lowering error.
235    fn unsupported_order_by_alias(alias: impl Into<String>) -> Self {
236        Self::UnsupportedOrderByAlias {
237            alias: alias.into(),
238        }
239    }
240}
241
242impl From<QueryError> for SqlLoweringError {
243    fn from(value: QueryError) -> Self {
244        Self::Query(Box::new(value))
245    }
246}
247
248///
249/// PreparedSqlStatement
250///
251/// SQL statement envelope after entity-scope normalization and
252/// entity-match validation for one target entity descriptor.
253///
254/// This pre-lowering contract is entity-agnostic and reusable across
255/// dynamic SQL route branches before typed `Query<E>` binding.
256///
257#[derive(Clone, Debug)]
258pub(crate) struct PreparedSqlStatement {
259    pub(in crate::db::sql::lowering) statement: SqlStatement,
260}
261
262impl PreparedSqlStatement {
263    /// Consume one prepared SQL statement back into its normalized parsed form.
264    #[must_use]
265    pub(in crate::db) fn into_statement(self) -> SqlStatement {
266        self.statement
267    }
268}
269
270#[derive(Clone, Copy, Debug, Eq, PartialEq)]
271pub(crate) enum LoweredSqlLaneKind {
272    Query,
273    Explain,
274    Describe,
275    ShowIndexes,
276    ShowColumns,
277    ShowEntities,
278}
279
280/// Parse and lower one SQL statement into canonical query intent for `E`.
281#[cfg(test)]
282pub(crate) fn compile_sql_command<E: EntityKind>(
283    sql: &str,
284    consistency: MissingRowPolicy,
285) -> Result<SqlCommand<E>, SqlLoweringError> {
286    let statement = crate::db::sql::parser::parse_sql(sql)?;
287
288    compile_sql_command_from_statement::<E>(statement, consistency)
289}
290
291/// Lower one parsed SQL statement into canonical query intent for `E`.
292#[cfg(test)]
293pub(crate) fn compile_sql_command_from_statement<E: EntityKind>(
294    statement: SqlStatement,
295    consistency: MissingRowPolicy,
296) -> Result<SqlCommand<E>, SqlLoweringError> {
297    let prepared = prepare_sql_statement(statement, E::MODEL.name())?;
298
299    compile_sql_command_from_prepared_statement::<E>(prepared, consistency)
300}
301
302/// Lower one prepared SQL statement into canonical query intent for `E`.
303#[cfg(test)]
304pub(crate) fn compile_sql_command_from_prepared_statement<E: EntityKind>(
305    prepared: PreparedSqlStatement,
306    consistency: MissingRowPolicy,
307) -> Result<SqlCommand<E>, SqlLoweringError> {
308    let lowered = lower_sql_command_from_prepared_statement(prepared, E::MODEL.primary_key.name)?;
309
310    bind_lowered_sql_command::<E>(lowered, consistency)
311}
312
313pub(crate) const fn lowered_sql_command_lane(command: &LoweredSqlCommand) -> LoweredSqlLaneKind {
314    match command.0 {
315        LoweredSqlCommandInner::Query(_) => LoweredSqlLaneKind::Query,
316        LoweredSqlCommandInner::Explain { .. }
317        | LoweredSqlCommandInner::ExplainGlobalAggregate { .. } => LoweredSqlLaneKind::Explain,
318        LoweredSqlCommandInner::DescribeEntity => LoweredSqlLaneKind::Describe,
319        LoweredSqlCommandInner::ShowIndexesEntity => LoweredSqlLaneKind::ShowIndexes,
320        LoweredSqlCommandInner::ShowColumnsEntity => LoweredSqlLaneKind::ShowColumns,
321        LoweredSqlCommandInner::ShowEntities => LoweredSqlLaneKind::ShowEntities,
322    }
323}
324
325/// Bind one shared generic-free SQL command shape to the typed query surface.
326#[cfg(test)]
327pub(crate) fn bind_lowered_sql_command<E: EntityKind>(
328    lowered: LoweredSqlCommand,
329    consistency: MissingRowPolicy,
330) -> Result<SqlCommand<E>, SqlLoweringError> {
331    match lowered.0 {
332        LoweredSqlCommandInner::Query(query) => Ok(SqlCommand::Query(bind_lowered_sql_query::<E>(
333            query,
334            consistency,
335        )?)),
336        LoweredSqlCommandInner::Explain { mode, query } => Ok(SqlCommand::Explain {
337            mode,
338            query: bind_lowered_sql_query::<E>(query, consistency)?,
339        }),
340        LoweredSqlCommandInner::ExplainGlobalAggregate { mode, command } => {
341            Ok(SqlCommand::ExplainGlobalAggregate {
342                mode,
343                command: aggregate::bind_lowered_sql_global_aggregate_command::<E>(
344                    command,
345                    consistency,
346                )?,
347            })
348        }
349        LoweredSqlCommandInner::DescribeEntity => Ok(SqlCommand::DescribeEntity),
350        LoweredSqlCommandInner::ShowIndexesEntity => Ok(SqlCommand::ShowIndexesEntity),
351        LoweredSqlCommandInner::ShowColumnsEntity => Ok(SqlCommand::ShowColumnsEntity),
352        LoweredSqlCommandInner::ShowEntities => Ok(SqlCommand::ShowEntities),
353    }
354}