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 analysis;
8mod expr;
9mod normalize;
10#[cfg(test)]
11mod order_expr;
12mod predicate;
13mod prepare;
14mod select;
15
16///
17/// TESTS
18///
19
20#[cfg(test)]
21mod tests;
22
23use crate::db::{
24    query::intent::QueryError,
25    sql::parser::{SqlExplainMode, SqlStatement},
26};
27#[cfg(test)]
28use crate::{
29    db::{predicate::MissingRowPolicy, query::intent::Query},
30    traits::EntityKind,
31};
32use thiserror::Error as ThisError;
33
34pub(in crate::db::sql::lowering) use aggregate::LoweredSqlGlobalAggregateCommand;
35pub(in crate::db) use aggregate::compile_sql_global_aggregate_command_core_from_prepared_with_schema;
36#[cfg(test)]
37pub(crate) use aggregate::{
38    PreparedSqlScalarAggregateDescriptorShape, SqlGlobalAggregateCommand,
39    compile_sql_global_aggregate_command_for_model_only,
40};
41pub(crate) use aggregate::{
42    PreparedSqlScalarAggregatePlanFragment, PreparedSqlScalarAggregateStrategy,
43};
44pub(crate) use aggregate::{
45    SqlGlobalAggregateCommandCore, bind_lowered_sql_explain_global_aggregate_structural_with_schema,
46};
47pub(in crate::db::sql::lowering) use analysis::{LoweredExprAnalysis, analyze_lowered_expr};
48#[cfg(test)]
49pub(in crate::db) use order_expr::{
50    lower_grouped_post_aggregate_order_expr_text, lower_supported_order_expr_text,
51};
52pub(in crate::db) use prepare::bind_prepared_sql_select_statement_structural_with_schema;
53#[cfg(test)]
54pub(crate) use prepare::lower_sql_command_from_prepared_statement_for_model_only;
55pub(crate) use prepare::{
56    extract_prepared_sql_insert_select_source, extract_prepared_sql_insert_statement,
57    extract_prepared_sql_update_statement, lower_prepared_sql_delete_statement,
58    lower_prepared_sql_select_statement_with_schema,
59    lower_sql_command_from_prepared_statement_with_schema, prepare_sql_statement,
60};
61pub(crate) use select::LoweredDeleteShape;
62pub(in crate::db::sql::lowering) use select::LoweredSqlFilter;
63#[cfg(test)]
64pub(in crate::db::sql::lowering) use select::apply_lowered_base_query_shape_for_model_only;
65pub(in crate::db::sql::lowering) use select::apply_lowered_base_query_shape_with_schema;
66#[cfg(test)]
67pub(in crate::db) use select::apply_lowered_select_shape_for_model_only;
68#[cfg(test)]
69pub(in crate::db) use select::bind_lowered_sql_query_for_model_only;
70pub(in crate::db::sql::lowering) use select::validate_base_query_sql_capabilities;
71pub(crate) use select::{LoweredBaseQueryShape, LoweredSelectShape};
72pub(in crate::db) use select::{
73    bind_lowered_sql_delete_query_structural_with_schema,
74    bind_lowered_sql_query_structural_with_schema,
75    bind_lowered_sql_select_query_structural_with_schema,
76    bind_sql_update_selector_query_structural_with_schema,
77};
78
79///
80/// LoweredSqlCommand
81///
82/// Generic-free SQL command shape after reduced SQL parsing and entity-route
83/// normalization.
84/// This keeps statement-shape lowering shared across entities before typed
85/// `Query<E>` binding happens at the execution boundary.
86///
87#[derive(Clone, Debug)]
88pub struct LoweredSqlCommand(pub(in crate::db::sql::lowering) LoweredSqlCommandInner);
89
90#[derive(Clone, Debug)]
91#[cfg_attr(not(test), allow(dead_code))]
92pub(in crate::db::sql::lowering) enum LoweredSqlCommandInner {
93    Query(LoweredSqlQuery),
94    Explain {
95        mode: SqlExplainMode,
96        verbose: bool,
97        query: LoweredSqlQuery,
98    },
99    ExplainGlobalAggregate {
100        mode: SqlExplainMode,
101        verbose: bool,
102        command: LoweredSqlGlobalAggregateCommand,
103    },
104    DescribeEntity,
105    ShowIndexesEntity,
106    ShowColumnsEntity,
107    ShowEntities,
108}
109
110///
111/// SqlCommand
112///
113/// Test-only typed SQL command shell over the shared lowered SQL surface.
114/// Runtime dispatch now consumes `LoweredSqlCommand` directly, but lowering
115/// tests still validate typed binding behavior on this local envelope.
116///
117#[cfg(test)]
118#[derive(Debug)]
119pub(crate) enum SqlCommand<E: EntityKind> {
120    Query(Query<E>),
121    GlobalAggregate(SqlGlobalAggregateCommand<E>),
122    Explain {
123        mode: SqlExplainMode,
124        verbose: bool,
125        query: Query<E>,
126    },
127    ExplainGlobalAggregate {
128        mode: SqlExplainMode,
129        verbose: bool,
130        command: SqlGlobalAggregateCommand<E>,
131    },
132    DescribeEntity,
133    ShowIndexesEntity,
134    ShowColumnsEntity,
135    ShowEntities,
136}
137
138impl LoweredSqlCommand {
139    #[cfg(test)]
140    #[must_use]
141    pub(in crate::db) const fn query(&self) -> Option<&LoweredSqlQuery> {
142        match &self.0 {
143            LoweredSqlCommandInner::Query(query) => Some(query),
144            LoweredSqlCommandInner::Explain { .. }
145            | LoweredSqlCommandInner::ExplainGlobalAggregate { .. }
146            | LoweredSqlCommandInner::DescribeEntity
147            | LoweredSqlCommandInner::ShowIndexesEntity
148            | LoweredSqlCommandInner::ShowColumnsEntity
149            | LoweredSqlCommandInner::ShowEntities => None,
150        }
151    }
152
153    #[cfg(test)]
154    #[must_use]
155    pub(in crate::db) fn into_query(self) -> Option<LoweredSqlQuery> {
156        match self.0 {
157            LoweredSqlCommandInner::Query(query) => Some(query),
158            LoweredSqlCommandInner::Explain { .. }
159            | LoweredSqlCommandInner::ExplainGlobalAggregate { .. }
160            | LoweredSqlCommandInner::DescribeEntity
161            | LoweredSqlCommandInner::ShowIndexesEntity
162            | LoweredSqlCommandInner::ShowColumnsEntity
163            | LoweredSqlCommandInner::ShowEntities => None,
164        }
165    }
166
167    #[must_use]
168    pub(in crate::db) const fn explain_query(
169        &self,
170    ) -> Option<(SqlExplainMode, bool, &LoweredSqlQuery)> {
171        match &self.0 {
172            LoweredSqlCommandInner::Explain {
173                mode,
174                verbose,
175                query,
176            } => Some((*mode, *verbose, query)),
177            LoweredSqlCommandInner::Query(_)
178            | LoweredSqlCommandInner::ExplainGlobalAggregate { .. }
179            | LoweredSqlCommandInner::DescribeEntity
180            | LoweredSqlCommandInner::ShowIndexesEntity
181            | LoweredSqlCommandInner::ShowColumnsEntity
182            | LoweredSqlCommandInner::ShowEntities => None,
183        }
184    }
185}
186
187///
188/// LoweredSqlQuery
189///
190/// Generic-free executable SQL query shape prepared before typed query binding.
191/// Select and delete lowering stay shared until the final `Query<E>` build.
192///
193#[derive(Clone, Debug)]
194pub(crate) enum LoweredSqlQuery {
195    Select(LoweredSelectShape),
196    Delete(LoweredBaseQueryShape),
197}
198
199///
200/// SqlLoweringError
201///
202/// SQL frontend lowering failures before planner validation/execution.
203///
204#[derive(Debug, ThisError)]
205pub(crate) enum SqlLoweringError {
206    #[error("{0}")]
207    Parse(#[from] crate::db::sql::parser::SqlParseError),
208
209    #[error("{0}")]
210    Query(Box<QueryError>),
211
212    #[error("SQL entity '{sql_entity}' does not match requested entity type '{expected_entity}'")]
213    EntityMismatch {
214        sql_entity: String,
215        expected_entity: String,
216    },
217
218    #[error(
219        "unsupported SQL SELECT projection; supported forms are SELECT *, field lists, global aggregate terminal lists, or grouped aggregate shapes"
220    )]
221    UnsupportedSelectProjection,
222
223    #[error("unsupported SQL SELECT DISTINCT")]
224    UnsupportedSelectDistinct,
225
226    #[error("SELECT DISTINCT ORDER BY terms must be derivable from the projected distinct tuple")]
227    DistinctOrderByRequiresProjectedTuple,
228
229    #[error(
230        "unsupported global aggregate SQL projection; supported forms are aggregate projections such as COUNT(*), SUM(field), AVG(expr), or scalar wrappers over aggregate results"
231    )]
232    UnsupportedGlobalAggregateProjection,
233
234    #[error("global aggregate SQL does not support GROUP BY")]
235    GlobalAggregateDoesNotSupportGroupBy,
236
237    #[error("unsupported SQL GROUP BY projection shape")]
238    UnsupportedSelectGroupBy,
239
240    #[error("grouped SELECT requires an explicit projection list")]
241    GroupedProjectionRequiresExplicitList,
242
243    #[error("grouped SELECT projection must include at least one aggregate expression")]
244    GroupedProjectionRequiresAggregate,
245
246    #[error(
247        "grouped projection expression at index={index} references fields outside GROUP BY keys"
248    )]
249    GroupedProjectionReferencesNonGroupField { index: usize },
250
251    #[error(
252        "grouped projection expression at index={index} appears after aggregate expressions started"
253    )]
254    GroupedProjectionScalarAfterAggregate { index: usize },
255
256    #[error("HAVING requires GROUP BY")]
257    HavingRequiresGroupBy,
258
259    #[error("unsupported SQL HAVING shape")]
260    UnsupportedSelectHaving,
261
262    #[error("aggregate input expressions are not executable in this release")]
263    UnsupportedAggregateInputExpressions,
264
265    #[error("unsupported SQL WHERE expression shape")]
266    UnsupportedWhereExpression,
267
268    #[error("unknown field '{field}'")]
269    UnknownField { field: String },
270
271    #[error("{message}")]
272    UnsupportedParameterPlacement { message: String },
273
274    #[error("SQL DDL execution is not supported in this release")]
275    UnsupportedSqlDdl,
276
277    #[error("query-lane lowering reached a non query-compatible statement")]
278    UnexpectedQueryLaneStatement,
279}
280
281impl SqlLoweringError {
282    /// Construct one entity-mismatch SQL lowering error.
283    fn entity_mismatch(sql_entity: impl Into<String>, expected_entity: impl Into<String>) -> Self {
284        Self::EntityMismatch {
285            sql_entity: sql_entity.into(),
286            expected_entity: expected_entity.into(),
287        }
288    }
289
290    /// Construct one unsupported SELECT projection SQL lowering error.
291    const fn unsupported_select_projection() -> Self {
292        Self::UnsupportedSelectProjection
293    }
294
295    /// Construct one query-lane lowering misuse error.
296    pub(crate) const fn unexpected_query_lane_statement() -> Self {
297        Self::UnexpectedQueryLaneStatement
298    }
299
300    /// Construct one unsupported SELECT DISTINCT SQL lowering error.
301    const fn unsupported_select_distinct() -> Self {
302        Self::UnsupportedSelectDistinct
303    }
304
305    /// Construct one DISTINCT ORDER BY projection-derivability SQL lowering error.
306    const fn distinct_order_by_requires_projected_tuple() -> Self {
307        Self::DistinctOrderByRequiresProjectedTuple
308    }
309
310    /// Construct one unsupported global aggregate projection SQL lowering error.
311    const fn unsupported_global_aggregate_projection() -> Self {
312        Self::UnsupportedGlobalAggregateProjection
313    }
314
315    /// Construct one unsupported SQL WHERE expression lowering error.
316    pub(crate) const fn unsupported_where_expression() -> Self {
317        Self::UnsupportedWhereExpression
318    }
319
320    /// Construct one global-aggregate-GROUP-BY SQL lowering error.
321    const fn global_aggregate_does_not_support_group_by() -> Self {
322        Self::GlobalAggregateDoesNotSupportGroupBy
323    }
324
325    /// Construct one unsupported SELECT GROUP BY shape SQL lowering error.
326    const fn unsupported_select_group_by() -> Self {
327        Self::UnsupportedSelectGroupBy
328    }
329
330    /// Construct one grouped-projection-explicit-list SQL lowering error.
331    const fn grouped_projection_requires_explicit_list() -> Self {
332        Self::GroupedProjectionRequiresExplicitList
333    }
334
335    /// Construct one grouped-projection-missing-aggregate SQL lowering error.
336    const fn grouped_projection_requires_aggregate() -> Self {
337        Self::GroupedProjectionRequiresAggregate
338    }
339
340    /// Construct one grouped projection non-group-field SQL lowering error.
341    const fn grouped_projection_references_non_group_field(index: usize) -> Self {
342        Self::GroupedProjectionReferencesNonGroupField { index }
343    }
344
345    /// Construct one grouped projection scalar-after-aggregate SQL lowering error.
346    const fn grouped_projection_scalar_after_aggregate(index: usize) -> Self {
347        Self::GroupedProjectionScalarAfterAggregate { index }
348    }
349
350    /// Construct one HAVING-requires-GROUP-BY SQL lowering error.
351    const fn having_requires_group_by() -> Self {
352        Self::HavingRequiresGroupBy
353    }
354
355    /// Construct one unsupported SELECT HAVING shape SQL lowering error.
356    const fn unsupported_select_having() -> Self {
357        Self::UnsupportedSelectHaving
358    }
359
360    /// Construct one aggregate-input execution seam SQL lowering error.
361    const fn unsupported_aggregate_input_expressions() -> Self {
362        Self::UnsupportedAggregateInputExpressions
363    }
364
365    /// Construct one unknown-field SQL lowering error.
366    pub(crate) fn unknown_field(field: impl Into<String>) -> Self {
367        Self::UnknownField {
368            field: field.into(),
369        }
370    }
371
372    /// Construct one unsupported parameter placement SQL lowering error.
373    pub(crate) fn unsupported_parameter_placement(
374        index: Option<usize>,
375        message: impl Into<String>,
376    ) -> Self {
377        let message = match index {
378            Some(index) => format!("parameter slot ${index}: {}", message.into()),
379            None => message.into(),
380        };
381
382        Self::UnsupportedParameterPlacement { message }
383    }
384
385    /// Construct one unsupported SQL DDL lowering error.
386    pub(crate) const fn unsupported_sql_ddl() -> Self {
387        Self::UnsupportedSqlDdl
388    }
389}
390
391impl From<QueryError> for SqlLoweringError {
392    fn from(value: QueryError) -> Self {
393        Self::Query(Box::new(value))
394    }
395}
396
397///
398/// PreparedSqlStatement
399///
400/// SQL statement envelope after entity-scope normalization and
401/// entity-match validation for one target entity descriptor.
402///
403/// This pre-lowering contract is entity-agnostic and reusable across
404/// dynamic SQL route branches before typed `Query<E>` binding.
405///
406#[derive(Clone, Debug)]
407pub(crate) struct PreparedSqlStatement {
408    pub(in crate::db::sql::lowering) statement: SqlStatement,
409}
410
411impl PreparedSqlStatement {
412    /// Borrow one prepared SQL statement in its normalized parsed form.
413    #[must_use]
414    pub(in crate::db) const fn statement(&self) -> &SqlStatement {
415        &self.statement
416    }
417
418    /// Consume one prepared SQL statement back into its normalized parsed form.
419    #[must_use]
420    pub(in crate::db) fn into_statement(self) -> SqlStatement {
421        self.statement
422    }
423}
424
425#[derive(Clone, Copy, Debug, Eq, PartialEq)]
426pub(crate) enum LoweredSqlLaneKind {
427    Query,
428    Explain,
429    Describe,
430    ShowIndexes,
431    ShowColumns,
432    ShowEntities,
433}
434
435/// Parse and lower one SQL statement into canonical query intent for `E`.
436#[cfg(test)]
437pub(crate) fn compile_sql_command<E: EntityKind>(
438    sql: &str,
439    consistency: MissingRowPolicy,
440) -> Result<SqlCommand<E>, SqlLoweringError> {
441    let statement = crate::db::sql::parser::parse_sql(sql)?;
442    let prepared = prepare_sql_statement(&statement, E::MODEL.name())?;
443
444    if prepared.statement().is_global_aggregate_lane_shape() {
445        return Ok(SqlCommand::GlobalAggregate(
446            aggregate::compile_sql_global_aggregate_command_from_prepared_for_model_only::<E>(
447                prepared,
448                consistency,
449            )?,
450        ));
451    }
452
453    let lowered = lower_sql_command_from_prepared_statement_for_model_only(prepared, E::MODEL)?;
454
455    // Keep the test-only typed envelope local to the single public test entry
456    // point instead of preserving a private forwarding chain.
457    match lowered.0 {
458        LoweredSqlCommandInner::Query(query) => Ok(SqlCommand::Query(
459            bind_lowered_sql_query_for_model_only::<E>(query, consistency)?,
460        )),
461        LoweredSqlCommandInner::ExplainGlobalAggregate {
462            mode,
463            verbose,
464            command,
465        } => Ok(SqlCommand::ExplainGlobalAggregate {
466            mode,
467            verbose,
468            command: aggregate::bind_lowered_sql_global_aggregate_command_for_model_only::<E>(
469                command,
470                consistency,
471            )?,
472        }),
473        LoweredSqlCommandInner::Explain {
474            mode,
475            verbose,
476            query,
477        } => Ok(SqlCommand::Explain {
478            mode,
479            verbose,
480            query: bind_lowered_sql_query_for_model_only::<E>(query, consistency)?,
481        }),
482        LoweredSqlCommandInner::DescribeEntity => Ok(SqlCommand::DescribeEntity),
483        LoweredSqlCommandInner::ShowIndexesEntity => Ok(SqlCommand::ShowIndexesEntity),
484        LoweredSqlCommandInner::ShowColumnsEntity => Ok(SqlCommand::ShowColumnsEntity),
485        LoweredSqlCommandInner::ShowEntities => Ok(SqlCommand::ShowEntities),
486    }
487}
488
489pub(crate) const fn lowered_sql_command_lane(command: &LoweredSqlCommand) -> LoweredSqlLaneKind {
490    match command.0 {
491        LoweredSqlCommandInner::Query(_) => LoweredSqlLaneKind::Query,
492        LoweredSqlCommandInner::Explain { .. }
493        | LoweredSqlCommandInner::ExplainGlobalAggregate { .. } => LoweredSqlLaneKind::Explain,
494        LoweredSqlCommandInner::DescribeEntity => LoweredSqlLaneKind::Describe,
495        LoweredSqlCommandInner::ShowIndexesEntity => LoweredSqlLaneKind::ShowIndexes,
496        LoweredSqlCommandInner::ShowColumnsEntity => LoweredSqlLaneKind::ShowColumns,
497        LoweredSqlCommandInner::ShowEntities => LoweredSqlLaneKind::ShowEntities,
498    }
499}