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};
52
53#[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#[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#[derive(Clone, Debug)]
155pub(crate) enum LoweredSqlQuery {
156 Select(LoweredSelectShape),
157 Delete(LoweredBaseQueryShape),
158}
159
160#[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, global aggregate terminal 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 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 const fn unsupported_select_projection() -> Self {
211 Self::UnsupportedSelectProjection
212 }
213
214 pub(crate) const fn unexpected_query_lane_statement() -> Self {
216 Self::UnexpectedQueryLaneStatement
217 }
218
219 const fn unsupported_select_distinct() -> Self {
221 Self::UnsupportedSelectDistinct
222 }
223
224 const fn unsupported_select_group_by() -> Self {
226 Self::UnsupportedSelectGroupBy
227 }
228
229 const fn unsupported_select_having() -> Self {
231 Self::UnsupportedSelectHaving
232 }
233
234 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#[derive(Clone, Debug)]
258pub(crate) struct PreparedSqlStatement {
259 pub(in crate::db::sql::lowering) statement: SqlStatement,
260}
261
262impl PreparedSqlStatement {
263 #[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#[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#[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#[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#[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}