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