icydb_core/db/sql/lowering/
mod.rs1mod aggregate;
7mod normalize;
8mod prepare;
9mod select;
10
11#[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#[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#[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#[derive(Clone, Debug)]
156pub(crate) enum LoweredSqlQuery {
157 Select(LoweredSelectShape),
158 Delete(LoweredBaseQueryShape),
159}
160
161#[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 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 const fn unsupported_select_projection() -> Self {
218 Self::UnsupportedSelectProjection
219 }
220
221 pub(crate) const fn unexpected_query_lane_statement() -> Self {
223 Self::UnexpectedQueryLaneStatement
224 }
225
226 const fn unsupported_select_distinct() -> Self {
228 Self::UnsupportedSelectDistinct
229 }
230
231 const fn unsupported_select_group_by() -> Self {
233 Self::UnsupportedSelectGroupBy
234 }
235
236 const fn unsupported_select_having() -> Self {
238 Self::UnsupportedSelectHaving
239 }
240
241 const fn unsupported_aggregate_input_expressions() -> Self {
243 Self::UnsupportedAggregateInputExpressions
244 }
245
246 fn unknown_field(field: impl Into<String>) -> Self {
248 Self::UnknownField {
249 field: field.into(),
250 }
251 }
252
253 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#[derive(Clone, Debug)]
277pub(crate) struct PreparedSqlStatement {
278 pub(in crate::db::sql::lowering) statement: SqlStatement,
279}
280
281impl PreparedSqlStatement {
282 #[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#[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 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}