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
6///
7/// TESTS
8///
9
10#[cfg(test)]
11mod tests;
12
13use crate::{
14    db::{
15        predicate::{MissingRowPolicy, Predicate},
16        query::{
17            builder::aggregate::{avg, count, count_by, max_by, min_by, sum},
18            intent::{Query, QueryError, StructuralQuery},
19        },
20        sql::identifier::{
21            identifier_last_segment, identifiers_tail_match, normalize_identifier_to_scope,
22            rewrite_field_identifiers,
23        },
24        sql::parser::{
25            SqlAggregateCall, SqlAggregateKind, SqlDeleteStatement, SqlExplainMode,
26            SqlExplainStatement, SqlExplainTarget, SqlHavingClause, SqlHavingSymbol,
27            SqlOrderDirection, SqlOrderTerm, SqlProjection, SqlSelectItem, SqlSelectStatement,
28            SqlStatement, SqlTextFunctionCall, parse_sql,
29        },
30    },
31    traits::EntityKind,
32};
33use thiserror::Error as ThisError;
34
35///
36/// LoweredSqlCommand
37///
38/// Generic-free SQL command shape after reduced SQL parsing and entity-route
39/// normalization.
40/// This keeps statement-shape lowering shared across entities before typed
41/// `Query<E>` binding happens at the execution boundary.
42///
43#[derive(Clone, Debug)]
44pub struct LoweredSqlCommand(LoweredSqlCommandInner);
45
46#[derive(Clone, Debug)]
47enum LoweredSqlCommandInner {
48    Query(LoweredSqlQuery),
49    Explain {
50        mode: SqlExplainMode,
51        query: LoweredSqlQuery,
52    },
53    ExplainGlobalAggregate {
54        mode: SqlExplainMode,
55        command: LoweredSqlGlobalAggregateCommand,
56    },
57    DescribeEntity,
58    ShowIndexesEntity,
59    ShowColumnsEntity,
60    ShowEntities,
61}
62
63///
64/// SqlCommand
65///
66/// Test-only typed SQL command shell over the shared lowered SQL surface.
67/// Runtime dispatch now consumes `LoweredSqlCommand` directly, but lowering
68/// tests still validate typed binding behavior on this local envelope.
69///
70#[cfg(test)]
71#[derive(Debug)]
72pub(crate) enum SqlCommand<E: EntityKind> {
73    Query(Query<E>),
74    Explain {
75        mode: SqlExplainMode,
76        query: Query<E>,
77    },
78    ExplainGlobalAggregate {
79        mode: SqlExplainMode,
80        command: SqlGlobalAggregateCommand<E>,
81    },
82    DescribeEntity,
83    ShowIndexesEntity,
84    ShowColumnsEntity,
85    ShowEntities,
86}
87
88impl LoweredSqlCommand {
89    #[must_use]
90    pub(in crate::db) const fn query(&self) -> Option<&LoweredSqlQuery> {
91        match &self.0 {
92            LoweredSqlCommandInner::Query(query) => Some(query),
93            LoweredSqlCommandInner::Explain { .. }
94            | LoweredSqlCommandInner::ExplainGlobalAggregate { .. }
95            | LoweredSqlCommandInner::DescribeEntity
96            | LoweredSqlCommandInner::ShowIndexesEntity
97            | LoweredSqlCommandInner::ShowColumnsEntity
98            | LoweredSqlCommandInner::ShowEntities => None,
99        }
100    }
101}
102
103///
104/// LoweredSqlQuery
105///
106/// Generic-free executable SQL query shape prepared before typed query binding.
107/// Select and delete lowering stay shared until the final `Query<E>` build.
108///
109#[derive(Clone, Debug)]
110pub(crate) enum LoweredSqlQuery {
111    Select(LoweredSelectShape),
112    Delete(LoweredBaseQueryShape),
113}
114
115impl LoweredSqlQuery {
116    // Report whether this lowered query carries grouped execution semantics.
117    pub(crate) const fn has_grouping(&self) -> bool {
118        match self {
119            Self::Select(select) => select.has_grouping(),
120            Self::Delete(_) => false,
121        }
122    }
123}
124
125///
126/// SqlGlobalAggregateTerminal
127///
128/// Global SQL aggregate terminals currently executable through dedicated
129/// aggregate SQL entrypoints.
130///
131
132#[derive(Clone, Debug, Eq, PartialEq)]
133pub(crate) enum SqlGlobalAggregateTerminal {
134    CountRows,
135    CountField(String),
136    SumField(String),
137    AvgField(String),
138    MinField(String),
139    MaxField(String),
140}
141
142///
143/// LoweredSqlGlobalAggregateCommand
144///
145/// Generic-free global aggregate command shape prepared before typed query
146/// binding.
147/// This keeps aggregate SQL lowering shared across entities until the final
148/// execution boundary converts the base query shape into `Query<E>`.
149///
150#[derive(Clone, Debug)]
151pub(crate) struct LoweredSqlGlobalAggregateCommand {
152    query: LoweredBaseQueryShape,
153    terminal: SqlGlobalAggregateTerminal,
154}
155
156///
157/// LoweredSqlAggregateShape
158///
159/// Locally validated aggregate-call shape used by SQL lowering to avoid
160/// duplicating `(SqlAggregateKind, field)` validation across lowering lanes.
161///
162
163enum LoweredSqlAggregateShape {
164    CountRows,
165    CountField(String),
166    FieldTarget {
167        kind: SqlAggregateKind,
168        field: String,
169    },
170}
171
172///
173/// SqlGlobalAggregateCommand
174///
175/// Lowered global SQL aggregate command carrying base query shape plus terminal.
176///
177
178#[derive(Debug)]
179pub(crate) struct SqlGlobalAggregateCommand<E: EntityKind> {
180    query: Query<E>,
181    terminal: SqlGlobalAggregateTerminal,
182}
183
184impl<E: EntityKind> SqlGlobalAggregateCommand<E> {
185    /// Borrow the lowered base query shape for aggregate execution.
186    #[must_use]
187    pub(crate) const fn query(&self) -> &Query<E> {
188        &self.query
189    }
190
191    /// Borrow the lowered aggregate terminal.
192    #[must_use]
193    pub(crate) const fn terminal(&self) -> &SqlGlobalAggregateTerminal {
194        &self.terminal
195    }
196}
197
198///
199/// SqlGlobalAggregateCommandCore
200///
201/// Generic-free lowered global aggregate command bound onto the structural
202/// query surface.
203/// This keeps global aggregate EXPLAIN on the shared query/explain path until
204/// a typed boundary is strictly required.
205///
206
207#[derive(Debug)]
208pub(crate) struct SqlGlobalAggregateCommandCore {
209    query: StructuralQuery,
210    terminal: SqlGlobalAggregateTerminal,
211}
212
213impl SqlGlobalAggregateCommandCore {
214    /// Borrow the structural query payload for aggregate explain/execution.
215    #[must_use]
216    pub(in crate::db) const fn query(&self) -> &StructuralQuery {
217        &self.query
218    }
219
220    /// Borrow the lowered aggregate terminal.
221    #[must_use]
222    pub(in crate::db) const fn terminal(&self) -> &SqlGlobalAggregateTerminal {
223        &self.terminal
224    }
225}
226
227///
228/// SqlLoweringError
229///
230/// SQL frontend lowering failures before planner validation/execution.
231///
232
233#[derive(Debug, ThisError)]
234pub(crate) enum SqlLoweringError {
235    #[error("{0}")]
236    Parse(#[from] crate::db::sql::parser::SqlParseError),
237
238    #[error("{0}")]
239    Query(#[from] QueryError),
240
241    #[error("SQL entity '{sql_entity}' does not match requested entity type '{expected_entity}'")]
242    EntityMismatch {
243        sql_entity: String,
244        expected_entity: &'static str,
245    },
246
247    #[error(
248        "unsupported SQL SELECT projection; supported forms are SELECT *, field lists, or grouped aggregate shapes"
249    )]
250    UnsupportedSelectProjection,
251
252    #[error("unsupported SQL SELECT DISTINCT")]
253    UnsupportedSelectDistinct,
254
255    #[error("unsupported SQL GROUP BY projection shape")]
256    UnsupportedSelectGroupBy,
257
258    #[error("unsupported SQL HAVING shape")]
259    UnsupportedSelectHaving,
260}
261
262impl SqlLoweringError {
263    /// Construct one entity-mismatch SQL lowering error.
264    fn entity_mismatch(sql_entity: impl Into<String>, expected_entity: &'static str) -> Self {
265        Self::EntityMismatch {
266            sql_entity: sql_entity.into(),
267            expected_entity,
268        }
269    }
270
271    /// Construct one unsupported SELECT projection SQL lowering error.
272    const fn unsupported_select_projection() -> Self {
273        Self::UnsupportedSelectProjection
274    }
275
276    /// Construct one unsupported SELECT DISTINCT SQL lowering error.
277    const fn unsupported_select_distinct() -> Self {
278        Self::UnsupportedSelectDistinct
279    }
280
281    /// Construct one unsupported SELECT GROUP BY shape SQL lowering error.
282    const fn unsupported_select_group_by() -> Self {
283        Self::UnsupportedSelectGroupBy
284    }
285
286    /// Construct one unsupported SELECT HAVING shape SQL lowering error.
287    const fn unsupported_select_having() -> Self {
288        Self::UnsupportedSelectHaving
289    }
290}
291
292///
293/// PreparedSqlStatement
294///
295/// SQL statement envelope after entity-scope normalization and
296/// entity-match validation for one target entity descriptor.
297///
298/// This pre-lowering contract is entity-agnostic and reusable across
299/// dynamic SQL route branches before typed `Query<E>` binding.
300///
301
302#[derive(Clone, Debug)]
303pub(crate) struct PreparedSqlStatement {
304    statement: SqlStatement,
305}
306
307#[derive(Clone, Copy, Debug, Eq, PartialEq)]
308pub(crate) enum LoweredSqlLaneKind {
309    Query,
310    Explain,
311    Describe,
312    ShowIndexes,
313    ShowColumns,
314    ShowEntities,
315}
316
317/// Parse and lower one SQL statement into canonical query intent for `E`.
318#[cfg(test)]
319pub(crate) fn compile_sql_command<E: EntityKind>(
320    sql: &str,
321    consistency: MissingRowPolicy,
322) -> Result<SqlCommand<E>, SqlLoweringError> {
323    let statement = parse_sql(sql)?;
324    compile_sql_command_from_statement::<E>(statement, consistency)
325}
326
327/// Lower one parsed SQL statement into canonical query intent for `E`.
328#[cfg(test)]
329pub(crate) fn compile_sql_command_from_statement<E: EntityKind>(
330    statement: SqlStatement,
331    consistency: MissingRowPolicy,
332) -> Result<SqlCommand<E>, SqlLoweringError> {
333    let prepared = prepare_sql_statement(statement, E::MODEL.name())?;
334    compile_sql_command_from_prepared_statement::<E>(prepared, consistency)
335}
336
337/// Lower one prepared SQL statement into canonical query intent for `E`.
338#[cfg(test)]
339pub(crate) fn compile_sql_command_from_prepared_statement<E: EntityKind>(
340    prepared: PreparedSqlStatement,
341    consistency: MissingRowPolicy,
342) -> Result<SqlCommand<E>, SqlLoweringError> {
343    let lowered = lower_sql_command_from_prepared_statement(prepared, E::MODEL.primary_key.name)?;
344
345    bind_lowered_sql_command::<E>(lowered, consistency)
346}
347
348/// Lower one prepared SQL statement into one shared generic-free command shape.
349#[inline(never)]
350pub(crate) fn lower_sql_command_from_prepared_statement(
351    prepared: PreparedSqlStatement,
352    primary_key_field: &str,
353) -> Result<LoweredSqlCommand, SqlLoweringError> {
354    lower_prepared_statement(prepared.statement, primary_key_field)
355}
356
357pub(crate) const fn lowered_sql_command_lane(command: &LoweredSqlCommand) -> LoweredSqlLaneKind {
358    match command.0 {
359        LoweredSqlCommandInner::Query(_) => LoweredSqlLaneKind::Query,
360        LoweredSqlCommandInner::Explain { .. }
361        | LoweredSqlCommandInner::ExplainGlobalAggregate { .. } => LoweredSqlLaneKind::Explain,
362        LoweredSqlCommandInner::DescribeEntity => LoweredSqlLaneKind::Describe,
363        LoweredSqlCommandInner::ShowIndexesEntity => LoweredSqlLaneKind::ShowIndexes,
364        LoweredSqlCommandInner::ShowColumnsEntity => LoweredSqlLaneKind::ShowColumns,
365        LoweredSqlCommandInner::ShowEntities => LoweredSqlLaneKind::ShowEntities,
366    }
367}
368
369/// Return whether one parsed SQL statement is an executable constrained global
370/// aggregate shape owned by the dedicated aggregate lane.
371pub(in crate::db) fn is_sql_global_aggregate_statement(statement: &SqlStatement) -> bool {
372    let SqlStatement::Select(statement) = statement else {
373        return false;
374    };
375
376    is_sql_global_aggregate_select(statement)
377}
378
379// Detect one constrained global aggregate select shape without widening any
380// non-aggregate SQL surface onto the dedicated aggregate execution lane.
381fn is_sql_global_aggregate_select(statement: &SqlSelectStatement) -> bool {
382    if statement.distinct || !statement.group_by.is_empty() || !statement.having.is_empty() {
383        return false;
384    }
385
386    lower_global_aggregate_terminal(statement.projection.clone()).is_ok()
387}
388
389/// Render one lowered EXPLAIN command through the shared structural SQL path.
390#[inline(never)]
391pub(crate) fn render_lowered_sql_explain_plan_or_json(
392    lowered: &LoweredSqlCommand,
393    model: &'static crate::model::entity::EntityModel,
394    consistency: MissingRowPolicy,
395) -> Result<Option<String>, SqlLoweringError> {
396    let LoweredSqlCommandInner::Explain { mode, query } = &lowered.0 else {
397        return Ok(None);
398    };
399
400    let query = bind_lowered_sql_query_structural(model, query.clone(), consistency)?;
401    let rendered = match mode {
402        SqlExplainMode::Plan | SqlExplainMode::Json => {
403            let plan = query.build_plan()?;
404            let explain = plan.explain_with_model(model);
405
406            match mode {
407                SqlExplainMode::Plan => explain.render_text_canonical(),
408                SqlExplainMode::Json => explain.render_json_canonical(),
409                SqlExplainMode::Execution => unreachable!("execution mode handled above"),
410            }
411        }
412        SqlExplainMode::Execution => query.explain_execution_text()?,
413    };
414
415    Ok(Some(rendered))
416}
417
418/// Bind one lowered global aggregate EXPLAIN shape onto the structural query
419/// surface when the explain command carries that specialized form.
420pub(crate) fn bind_lowered_sql_explain_global_aggregate_structural(
421    lowered: &LoweredSqlCommand,
422    model: &'static crate::model::entity::EntityModel,
423    consistency: MissingRowPolicy,
424) -> Option<(SqlExplainMode, SqlGlobalAggregateCommandCore)> {
425    let LoweredSqlCommandInner::ExplainGlobalAggregate { mode, command } = &lowered.0 else {
426        return None;
427    };
428
429    Some((
430        *mode,
431        bind_lowered_sql_global_aggregate_command_structural(model, command.clone(), consistency),
432    ))
433}
434
435/// Bind one shared generic-free SQL command shape to the typed query surface.
436#[cfg(test)]
437pub(crate) fn bind_lowered_sql_command<E: EntityKind>(
438    lowered: LoweredSqlCommand,
439    consistency: MissingRowPolicy,
440) -> Result<SqlCommand<E>, SqlLoweringError> {
441    match lowered.0 {
442        LoweredSqlCommandInner::Query(query) => Ok(SqlCommand::Query(bind_lowered_sql_query::<E>(
443            query,
444            consistency,
445        )?)),
446        LoweredSqlCommandInner::Explain { mode, query } => Ok(SqlCommand::Explain {
447            mode,
448            query: bind_lowered_sql_query::<E>(query, consistency)?,
449        }),
450        LoweredSqlCommandInner::ExplainGlobalAggregate { mode, command } => {
451            Ok(SqlCommand::ExplainGlobalAggregate {
452                mode,
453                command: bind_lowered_sql_global_aggregate_command::<E>(command, consistency),
454            })
455        }
456        LoweredSqlCommandInner::DescribeEntity => Ok(SqlCommand::DescribeEntity),
457        LoweredSqlCommandInner::ShowIndexesEntity => Ok(SqlCommand::ShowIndexesEntity),
458        LoweredSqlCommandInner::ShowColumnsEntity => Ok(SqlCommand::ShowColumnsEntity),
459        LoweredSqlCommandInner::ShowEntities => Ok(SqlCommand::ShowEntities),
460    }
461}
462
463/// Prepare one parsed SQL statement for one expected entity route.
464#[inline(never)]
465pub(crate) fn prepare_sql_statement(
466    statement: SqlStatement,
467    expected_entity: &'static str,
468) -> Result<PreparedSqlStatement, SqlLoweringError> {
469    let statement = prepare_statement(statement, expected_entity)?;
470
471    Ok(PreparedSqlStatement { statement })
472}
473
474/// Parse and lower one SQL statement into global aggregate execution command for `E`.
475pub(crate) fn compile_sql_global_aggregate_command<E: EntityKind>(
476    sql: &str,
477    consistency: MissingRowPolicy,
478) -> Result<SqlGlobalAggregateCommand<E>, SqlLoweringError> {
479    let statement = parse_sql(sql)?;
480    let prepared = prepare_sql_statement(statement, E::MODEL.name())?;
481    compile_sql_global_aggregate_command_from_prepared::<E>(prepared, consistency)
482}
483
484fn compile_sql_global_aggregate_command_from_prepared<E: EntityKind>(
485    prepared: PreparedSqlStatement,
486    consistency: MissingRowPolicy,
487) -> Result<SqlGlobalAggregateCommand<E>, SqlLoweringError> {
488    let SqlStatement::Select(statement) = prepared.statement else {
489        return Err(SqlLoweringError::unsupported_select_projection());
490    };
491
492    Ok(bind_lowered_sql_global_aggregate_command::<E>(
493        lower_global_aggregate_select_shape(statement)?,
494        consistency,
495    ))
496}
497
498#[inline(never)]
499fn prepare_statement(
500    statement: SqlStatement,
501    expected_entity: &'static str,
502) -> Result<SqlStatement, SqlLoweringError> {
503    match statement {
504        SqlStatement::Select(statement) => Ok(SqlStatement::Select(prepare_select_statement(
505            statement,
506            expected_entity,
507        )?)),
508        SqlStatement::Delete(statement) => Ok(SqlStatement::Delete(prepare_delete_statement(
509            statement,
510            expected_entity,
511        )?)),
512        SqlStatement::Explain(statement) => Ok(SqlStatement::Explain(prepare_explain_statement(
513            statement,
514            expected_entity,
515        )?)),
516        SqlStatement::Describe(statement) => {
517            ensure_entity_matches_expected(statement.entity.as_str(), expected_entity)?;
518
519            Ok(SqlStatement::Describe(statement))
520        }
521        SqlStatement::ShowIndexes(statement) => {
522            ensure_entity_matches_expected(statement.entity.as_str(), expected_entity)?;
523
524            Ok(SqlStatement::ShowIndexes(statement))
525        }
526        SqlStatement::ShowColumns(statement) => {
527            ensure_entity_matches_expected(statement.entity.as_str(), expected_entity)?;
528
529            Ok(SqlStatement::ShowColumns(statement))
530        }
531        SqlStatement::ShowEntities(statement) => Ok(SqlStatement::ShowEntities(statement)),
532    }
533}
534
535fn prepare_explain_statement(
536    statement: SqlExplainStatement,
537    expected_entity: &'static str,
538) -> Result<SqlExplainStatement, SqlLoweringError> {
539    let target = match statement.statement {
540        SqlExplainTarget::Select(select_statement) => {
541            SqlExplainTarget::Select(prepare_select_statement(select_statement, expected_entity)?)
542        }
543        SqlExplainTarget::Delete(delete_statement) => {
544            SqlExplainTarget::Delete(prepare_delete_statement(delete_statement, expected_entity)?)
545        }
546    };
547
548    Ok(SqlExplainStatement {
549        mode: statement.mode,
550        statement: target,
551    })
552}
553
554fn prepare_select_statement(
555    statement: SqlSelectStatement,
556    expected_entity: &'static str,
557) -> Result<SqlSelectStatement, SqlLoweringError> {
558    ensure_entity_matches_expected(statement.entity.as_str(), expected_entity)?;
559
560    Ok(normalize_select_statement_to_expected_entity(
561        statement,
562        expected_entity,
563    ))
564}
565
566fn normalize_select_statement_to_expected_entity(
567    mut statement: SqlSelectStatement,
568    expected_entity: &'static str,
569) -> SqlSelectStatement {
570    // Re-scope parsed identifiers onto the resolved entity surface after the
571    // caller has already established entity ownership for this statement.
572    let entity_scope = sql_entity_scope_candidates(statement.entity.as_str(), expected_entity);
573    statement.projection =
574        normalize_projection_identifiers(statement.projection, entity_scope.as_slice());
575    statement.group_by = normalize_identifier_list(statement.group_by, entity_scope.as_slice());
576    statement.predicate = statement
577        .predicate
578        .map(|predicate| adapt_predicate_identifiers_to_scope(predicate, entity_scope.as_slice()));
579    statement.order_by = normalize_order_terms(statement.order_by, entity_scope.as_slice());
580    statement.having = normalize_having_clauses(statement.having, entity_scope.as_slice());
581
582    statement
583}
584
585fn prepare_delete_statement(
586    mut statement: SqlDeleteStatement,
587    expected_entity: &'static str,
588) -> Result<SqlDeleteStatement, SqlLoweringError> {
589    ensure_entity_matches_expected(statement.entity.as_str(), expected_entity)?;
590    let entity_scope = sql_entity_scope_candidates(statement.entity.as_str(), expected_entity);
591    statement.predicate = statement
592        .predicate
593        .map(|predicate| adapt_predicate_identifiers_to_scope(predicate, entity_scope.as_slice()));
594    statement.order_by = normalize_order_terms(statement.order_by, entity_scope.as_slice());
595
596    Ok(statement)
597}
598
599#[inline(never)]
600fn lower_prepared_statement(
601    statement: SqlStatement,
602    primary_key_field: &str,
603) -> Result<LoweredSqlCommand, SqlLoweringError> {
604    match statement {
605        SqlStatement::Select(statement) => Ok(LoweredSqlCommand(LoweredSqlCommandInner::Query(
606            LoweredSqlQuery::Select(lower_select_shape(statement, primary_key_field)?),
607        ))),
608        SqlStatement::Delete(statement) => Ok(LoweredSqlCommand(LoweredSqlCommandInner::Query(
609            LoweredSqlQuery::Delete(lower_delete_shape(statement)),
610        ))),
611        SqlStatement::Explain(statement) => lower_explain_prepared(statement, primary_key_field),
612        SqlStatement::Describe(_) => Ok(LoweredSqlCommand(LoweredSqlCommandInner::DescribeEntity)),
613        SqlStatement::ShowIndexes(_) => {
614            Ok(LoweredSqlCommand(LoweredSqlCommandInner::ShowIndexesEntity))
615        }
616        SqlStatement::ShowColumns(_) => {
617            Ok(LoweredSqlCommand(LoweredSqlCommandInner::ShowColumnsEntity))
618        }
619        SqlStatement::ShowEntities(_) => {
620            Ok(LoweredSqlCommand(LoweredSqlCommandInner::ShowEntities))
621        }
622    }
623}
624
625fn lower_explain_prepared(
626    statement: SqlExplainStatement,
627    primary_key_field: &str,
628) -> Result<LoweredSqlCommand, SqlLoweringError> {
629    let mode = statement.mode;
630
631    match statement.statement {
632        SqlExplainTarget::Select(select_statement) => {
633            lower_explain_select_prepared(select_statement, mode, primary_key_field)
634        }
635        SqlExplainTarget::Delete(delete_statement) => {
636            Ok(LoweredSqlCommand(LoweredSqlCommandInner::Explain {
637                mode,
638                query: LoweredSqlQuery::Delete(lower_delete_shape(delete_statement)),
639            }))
640        }
641    }
642}
643
644fn lower_explain_select_prepared(
645    statement: SqlSelectStatement,
646    mode: SqlExplainMode,
647    primary_key_field: &str,
648) -> Result<LoweredSqlCommand, SqlLoweringError> {
649    match lower_select_shape(statement.clone(), primary_key_field) {
650        Ok(query) => Ok(LoweredSqlCommand(LoweredSqlCommandInner::Explain {
651            mode,
652            query: LoweredSqlQuery::Select(query),
653        })),
654        Err(SqlLoweringError::UnsupportedSelectProjection) => {
655            let command = lower_global_aggregate_select_shape(statement)?;
656
657            Ok(LoweredSqlCommand(
658                LoweredSqlCommandInner::ExplainGlobalAggregate { mode, command },
659            ))
660        }
661        Err(err) => Err(err),
662    }
663}
664
665fn lower_global_aggregate_select_shape(
666    statement: SqlSelectStatement,
667) -> Result<LoweredSqlGlobalAggregateCommand, SqlLoweringError> {
668    let SqlSelectStatement {
669        projection,
670        predicate,
671        distinct,
672        group_by,
673        having,
674        order_by,
675        limit,
676        offset,
677        entity: _,
678    } = statement;
679
680    if distinct {
681        return Err(SqlLoweringError::unsupported_select_distinct());
682    }
683    if !group_by.is_empty() {
684        return Err(SqlLoweringError::unsupported_select_group_by());
685    }
686    if !having.is_empty() {
687        return Err(SqlLoweringError::unsupported_select_having());
688    }
689
690    let terminal = lower_global_aggregate_terminal(projection)?;
691
692    Ok(LoweredSqlGlobalAggregateCommand {
693        query: LoweredBaseQueryShape {
694            predicate,
695            order_by,
696            limit,
697            offset,
698        },
699        terminal,
700    })
701}
702
703///
704/// ResolvedHavingClause
705///
706/// Pre-resolved HAVING clause shape after SQL projection aggregate index
707/// resolution. This keeps SQL shape analysis entity-agnostic before typed
708/// query binding.
709///
710#[derive(Clone, Debug)]
711enum ResolvedHavingClause {
712    GroupField {
713        field: String,
714        op: crate::db::predicate::CompareOp,
715        value: crate::value::Value,
716    },
717    Aggregate {
718        aggregate_index: usize,
719        op: crate::db::predicate::CompareOp,
720        value: crate::value::Value,
721    },
722}
723
724///
725/// LoweredSelectShape
726///
727/// Entity-agnostic lowered SQL SELECT shape prepared for typed `Query<E>`
728/// binding.
729///
730#[derive(Clone, Debug)]
731pub(crate) struct LoweredSelectShape {
732    scalar_projection_fields: Option<Vec<String>>,
733    grouped_projection_aggregates: Vec<SqlAggregateCall>,
734    group_by_fields: Vec<String>,
735    distinct: bool,
736    having: Vec<ResolvedHavingClause>,
737    predicate: Option<Predicate>,
738    order_by: Vec<crate::db::sql::parser::SqlOrderTerm>,
739    limit: Option<u32>,
740    offset: Option<u32>,
741}
742
743impl LoweredSelectShape {
744    // Report whether this lowered select shape carries grouped execution state.
745    const fn has_grouping(&self) -> bool {
746        !self.group_by_fields.is_empty()
747    }
748}
749
750///
751/// LoweredBaseQueryShape
752///
753/// Generic-free filter/order/window query modifiers shared by delete and
754/// global-aggregate SQL lowering.
755/// This keeps common SQL query-shape lowering shared before typed query
756/// binding.
757///
758#[derive(Clone, Debug)]
759pub(crate) struct LoweredBaseQueryShape {
760    predicate: Option<Predicate>,
761    order_by: Vec<SqlOrderTerm>,
762    limit: Option<u32>,
763    offset: Option<u32>,
764}
765
766#[inline(never)]
767fn lower_select_shape(
768    statement: SqlSelectStatement,
769    primary_key_field: &str,
770) -> Result<LoweredSelectShape, SqlLoweringError> {
771    let SqlSelectStatement {
772        projection,
773        predicate,
774        distinct,
775        group_by,
776        having,
777        order_by,
778        limit,
779        offset,
780        entity: _,
781    } = statement;
782    let projection_for_having = projection.clone();
783
784    // Phase 1: resolve scalar/grouped projection shape.
785    let (scalar_projection_fields, grouped_projection_aggregates) = if group_by.is_empty() {
786        let scalar_projection_fields =
787            lower_scalar_projection_fields(projection, distinct, primary_key_field)?;
788        (scalar_projection_fields, Vec::new())
789    } else {
790        if distinct {
791            return Err(SqlLoweringError::unsupported_select_distinct());
792        }
793        let grouped_projection_aggregates =
794            grouped_projection_aggregate_calls(&projection, group_by.as_slice())?;
795        (None, grouped_projection_aggregates)
796    };
797
798    // Phase 2: resolve HAVING symbols against grouped projection authority.
799    let having = lower_having_clauses(
800        having,
801        &projection_for_having,
802        group_by.as_slice(),
803        grouped_projection_aggregates.as_slice(),
804    )?;
805
806    Ok(LoweredSelectShape {
807        scalar_projection_fields,
808        grouped_projection_aggregates,
809        group_by_fields: group_by,
810        distinct,
811        having,
812        predicate,
813        order_by,
814        limit,
815        offset,
816    })
817}
818
819fn lower_scalar_projection_fields(
820    projection: SqlProjection,
821    distinct: bool,
822    primary_key_field: &str,
823) -> Result<Option<Vec<String>>, SqlLoweringError> {
824    let SqlProjection::Items(items) = projection else {
825        if distinct {
826            return Ok(None);
827        }
828
829        return Ok(None);
830    };
831
832    let has_aggregate = items
833        .iter()
834        .any(|item| matches!(item, SqlSelectItem::Aggregate(_)));
835    if has_aggregate {
836        return Err(SqlLoweringError::unsupported_select_projection());
837    }
838
839    let fields = items
840        .into_iter()
841        .map(|item| match item {
842            SqlSelectItem::Field(field) => Ok(field),
843            SqlSelectItem::Aggregate(_) | SqlSelectItem::TextFunction(_) => {
844                Err(SqlLoweringError::unsupported_select_projection())
845            }
846        })
847        .collect::<Result<Vec<_>, _>>()?;
848
849    validate_scalar_distinct_projection(distinct, fields.as_slice(), primary_key_field)?;
850
851    Ok(Some(fields))
852}
853
854fn validate_scalar_distinct_projection(
855    distinct: bool,
856    projection_fields: &[String],
857    primary_key_field: &str,
858) -> Result<(), SqlLoweringError> {
859    if !distinct {
860        return Ok(());
861    }
862
863    if projection_fields.is_empty() {
864        return Ok(());
865    }
866
867    let has_primary_key_field = projection_fields
868        .iter()
869        .any(|field| field == primary_key_field);
870    if !has_primary_key_field {
871        return Err(SqlLoweringError::unsupported_select_distinct());
872    }
873
874    Ok(())
875}
876
877fn lower_having_clauses(
878    having_clauses: Vec<SqlHavingClause>,
879    projection: &SqlProjection,
880    group_by_fields: &[String],
881    grouped_projection_aggregates: &[SqlAggregateCall],
882) -> Result<Vec<ResolvedHavingClause>, SqlLoweringError> {
883    if having_clauses.is_empty() {
884        return Ok(Vec::new());
885    }
886    if group_by_fields.is_empty() {
887        return Err(SqlLoweringError::unsupported_select_having());
888    }
889
890    let projection_aggregates = grouped_projection_aggregate_calls(projection, group_by_fields)
891        .map_err(|_| SqlLoweringError::unsupported_select_having())?;
892    if projection_aggregates.as_slice() != grouped_projection_aggregates {
893        return Err(SqlLoweringError::unsupported_select_having());
894    }
895
896    let mut lowered = Vec::with_capacity(having_clauses.len());
897    for clause in having_clauses {
898        match clause.symbol {
899            SqlHavingSymbol::Field(field) => lowered.push(ResolvedHavingClause::GroupField {
900                field,
901                op: clause.op,
902                value: clause.value,
903            }),
904            SqlHavingSymbol::Aggregate(aggregate) => {
905                let aggregate_index =
906                    resolve_having_aggregate_index(&aggregate, grouped_projection_aggregates)?;
907                lowered.push(ResolvedHavingClause::Aggregate {
908                    aggregate_index,
909                    op: clause.op,
910                    value: clause.value,
911                });
912            }
913        }
914    }
915
916    Ok(lowered)
917}
918
919#[inline(never)]
920pub(in crate::db) fn apply_lowered_select_shape(
921    mut query: StructuralQuery,
922    lowered: LoweredSelectShape,
923) -> Result<StructuralQuery, SqlLoweringError> {
924    let LoweredSelectShape {
925        scalar_projection_fields,
926        grouped_projection_aggregates,
927        group_by_fields,
928        distinct,
929        having,
930        predicate,
931        order_by,
932        limit,
933        offset,
934    } = lowered;
935
936    // Phase 1: apply grouped declaration semantics.
937    for field in group_by_fields {
938        query = query.group_by(field)?;
939    }
940
941    // Phase 2: apply scalar DISTINCT and projection contracts.
942    if distinct {
943        query = query.distinct();
944    }
945    if let Some(fields) = scalar_projection_fields {
946        query = query.select_fields(fields);
947    }
948    for aggregate in grouped_projection_aggregates {
949        query = query.aggregate(lower_aggregate_call(aggregate)?);
950    }
951
952    // Phase 3: bind resolved HAVING clauses against grouped terminals.
953    for clause in having {
954        match clause {
955            ResolvedHavingClause::GroupField { field, op, value } => {
956                query = query.having_group(field, op, value)?;
957            }
958            ResolvedHavingClause::Aggregate {
959                aggregate_index,
960                op,
961                value,
962            } => {
963                query = query.having_aggregate(aggregate_index, op, value)?;
964            }
965        }
966    }
967
968    // Phase 4: attach the shared filter/order/page tail through the base-query lane.
969    Ok(apply_lowered_base_query_shape(
970        query,
971        LoweredBaseQueryShape {
972            predicate,
973            order_by,
974            limit,
975            offset,
976        },
977    ))
978}
979
980fn apply_lowered_base_query_shape(
981    mut query: StructuralQuery,
982    lowered: LoweredBaseQueryShape,
983) -> StructuralQuery {
984    if let Some(predicate) = lowered.predicate {
985        query = query.filter(predicate);
986    }
987    query = apply_order_terms_structural(query, lowered.order_by);
988    if let Some(limit) = lowered.limit {
989        query = query.limit(limit);
990    }
991    if let Some(offset) = lowered.offset {
992        query = query.offset(offset);
993    }
994
995    query
996}
997
998pub(in crate::db) fn bind_lowered_sql_query_structural(
999    model: &'static crate::model::entity::EntityModel,
1000    lowered: LoweredSqlQuery,
1001    consistency: MissingRowPolicy,
1002) -> Result<StructuralQuery, SqlLoweringError> {
1003    match lowered {
1004        LoweredSqlQuery::Select(select) => {
1005            apply_lowered_select_shape(StructuralQuery::new(model, consistency), select)
1006        }
1007        LoweredSqlQuery::Delete(delete) => Ok(bind_lowered_sql_delete_query_structural(
1008            model,
1009            delete,
1010            consistency,
1011        )),
1012    }
1013}
1014
1015pub(in crate::db) fn bind_lowered_sql_delete_query_structural(
1016    model: &'static crate::model::entity::EntityModel,
1017    delete: LoweredBaseQueryShape,
1018    consistency: MissingRowPolicy,
1019) -> StructuralQuery {
1020    apply_lowered_base_query_shape(StructuralQuery::new(model, consistency).delete(), delete)
1021}
1022
1023pub(in crate::db) fn bind_lowered_sql_query<E: EntityKind>(
1024    lowered: LoweredSqlQuery,
1025    consistency: MissingRowPolicy,
1026) -> Result<Query<E>, SqlLoweringError> {
1027    let structural = bind_lowered_sql_query_structural(E::MODEL, lowered, consistency)?;
1028
1029    Ok(Query::from_inner(structural))
1030}
1031
1032fn bind_lowered_sql_global_aggregate_command<E: EntityKind>(
1033    lowered: LoweredSqlGlobalAggregateCommand,
1034    consistency: MissingRowPolicy,
1035) -> SqlGlobalAggregateCommand<E> {
1036    SqlGlobalAggregateCommand {
1037        query: Query::from_inner(apply_lowered_base_query_shape(
1038            StructuralQuery::new(E::MODEL, consistency),
1039            lowered.query,
1040        )),
1041        terminal: lowered.terminal,
1042    }
1043}
1044
1045fn bind_lowered_sql_global_aggregate_command_structural(
1046    model: &'static crate::model::entity::EntityModel,
1047    lowered: LoweredSqlGlobalAggregateCommand,
1048    consistency: MissingRowPolicy,
1049) -> SqlGlobalAggregateCommandCore {
1050    SqlGlobalAggregateCommandCore {
1051        query: apply_lowered_base_query_shape(
1052            StructuralQuery::new(model, consistency),
1053            lowered.query,
1054        ),
1055        terminal: lowered.terminal,
1056    }
1057}
1058
1059fn lower_global_aggregate_terminal(
1060    projection: SqlProjection,
1061) -> Result<SqlGlobalAggregateTerminal, SqlLoweringError> {
1062    let SqlProjection::Items(items) = projection else {
1063        return Err(SqlLoweringError::unsupported_select_projection());
1064    };
1065    if items.len() != 1 {
1066        return Err(SqlLoweringError::unsupported_select_projection());
1067    }
1068
1069    let Some(SqlSelectItem::Aggregate(aggregate)) = items.into_iter().next() else {
1070        return Err(SqlLoweringError::unsupported_select_projection());
1071    };
1072
1073    match lower_sql_aggregate_shape(aggregate)? {
1074        LoweredSqlAggregateShape::CountRows => Ok(SqlGlobalAggregateTerminal::CountRows),
1075        LoweredSqlAggregateShape::CountField(field) => {
1076            Ok(SqlGlobalAggregateTerminal::CountField(field))
1077        }
1078        LoweredSqlAggregateShape::FieldTarget {
1079            kind: SqlAggregateKind::Sum,
1080            field,
1081        } => Ok(SqlGlobalAggregateTerminal::SumField(field)),
1082        LoweredSqlAggregateShape::FieldTarget {
1083            kind: SqlAggregateKind::Avg,
1084            field,
1085        } => Ok(SqlGlobalAggregateTerminal::AvgField(field)),
1086        LoweredSqlAggregateShape::FieldTarget {
1087            kind: SqlAggregateKind::Min,
1088            field,
1089        } => Ok(SqlGlobalAggregateTerminal::MinField(field)),
1090        LoweredSqlAggregateShape::FieldTarget {
1091            kind: SqlAggregateKind::Max,
1092            field,
1093        } => Ok(SqlGlobalAggregateTerminal::MaxField(field)),
1094        LoweredSqlAggregateShape::FieldTarget {
1095            kind: SqlAggregateKind::Count,
1096            ..
1097        } => Err(SqlLoweringError::unsupported_select_projection()),
1098    }
1099}
1100
1101fn lower_sql_aggregate_shape(
1102    call: SqlAggregateCall,
1103) -> Result<LoweredSqlAggregateShape, SqlLoweringError> {
1104    match (call.kind, call.field) {
1105        (SqlAggregateKind::Count, None) => Ok(LoweredSqlAggregateShape::CountRows),
1106        (SqlAggregateKind::Count, Some(field)) => Ok(LoweredSqlAggregateShape::CountField(field)),
1107        (
1108            kind @ (SqlAggregateKind::Sum
1109            | SqlAggregateKind::Avg
1110            | SqlAggregateKind::Min
1111            | SqlAggregateKind::Max),
1112            Some(field),
1113        ) => Ok(LoweredSqlAggregateShape::FieldTarget { kind, field }),
1114        _ => Err(SqlLoweringError::unsupported_select_projection()),
1115    }
1116}
1117
1118fn grouped_projection_aggregate_calls(
1119    projection: &SqlProjection,
1120    group_by_fields: &[String],
1121) -> Result<Vec<SqlAggregateCall>, SqlLoweringError> {
1122    if group_by_fields.is_empty() {
1123        return Err(SqlLoweringError::unsupported_select_group_by());
1124    }
1125
1126    let SqlProjection::Items(items) = projection else {
1127        return Err(SqlLoweringError::unsupported_select_group_by());
1128    };
1129
1130    let mut projected_group_fields = Vec::<String>::new();
1131    let mut aggregate_calls = Vec::<SqlAggregateCall>::new();
1132    let mut seen_aggregate = false;
1133
1134    for item in items {
1135        match item {
1136            SqlSelectItem::Field(field) => {
1137                // Keep grouped projection deterministic and mappable to grouped
1138                // response contracts: group keys must be declared first.
1139                if seen_aggregate {
1140                    return Err(SqlLoweringError::unsupported_select_group_by());
1141                }
1142                projected_group_fields.push(field.clone());
1143            }
1144            SqlSelectItem::Aggregate(aggregate) => {
1145                seen_aggregate = true;
1146                aggregate_calls.push(aggregate.clone());
1147            }
1148            SqlSelectItem::TextFunction(_) => {
1149                return Err(SqlLoweringError::unsupported_select_group_by());
1150            }
1151        }
1152    }
1153
1154    if aggregate_calls.is_empty() || projected_group_fields.as_slice() != group_by_fields {
1155        return Err(SqlLoweringError::unsupported_select_group_by());
1156    }
1157
1158    Ok(aggregate_calls)
1159}
1160
1161fn lower_aggregate_call(
1162    call: SqlAggregateCall,
1163) -> Result<crate::db::query::builder::AggregateExpr, SqlLoweringError> {
1164    match lower_sql_aggregate_shape(call)? {
1165        LoweredSqlAggregateShape::CountRows => Ok(count()),
1166        LoweredSqlAggregateShape::CountField(field) => Ok(count_by(field)),
1167        LoweredSqlAggregateShape::FieldTarget {
1168            kind: SqlAggregateKind::Sum,
1169            field,
1170        } => Ok(sum(field)),
1171        LoweredSqlAggregateShape::FieldTarget {
1172            kind: SqlAggregateKind::Avg,
1173            field,
1174        } => Ok(avg(field)),
1175        LoweredSqlAggregateShape::FieldTarget {
1176            kind: SqlAggregateKind::Min,
1177            field,
1178        } => Ok(min_by(field)),
1179        LoweredSqlAggregateShape::FieldTarget {
1180            kind: SqlAggregateKind::Max,
1181            field,
1182        } => Ok(max_by(field)),
1183        LoweredSqlAggregateShape::FieldTarget {
1184            kind: SqlAggregateKind::Count,
1185            ..
1186        } => Err(SqlLoweringError::unsupported_select_projection()),
1187    }
1188}
1189
1190fn resolve_having_aggregate_index(
1191    target: &SqlAggregateCall,
1192    grouped_projection_aggregates: &[SqlAggregateCall],
1193) -> Result<usize, SqlLoweringError> {
1194    let mut matched = grouped_projection_aggregates
1195        .iter()
1196        .enumerate()
1197        .filter_map(|(index, aggregate)| (aggregate == target).then_some(index));
1198    let Some(index) = matched.next() else {
1199        return Err(SqlLoweringError::unsupported_select_having());
1200    };
1201    if matched.next().is_some() {
1202        return Err(SqlLoweringError::unsupported_select_having());
1203    }
1204
1205    Ok(index)
1206}
1207
1208fn lower_delete_shape(statement: SqlDeleteStatement) -> LoweredBaseQueryShape {
1209    let SqlDeleteStatement {
1210        predicate,
1211        order_by,
1212        limit,
1213        entity: _,
1214    } = statement;
1215
1216    LoweredBaseQueryShape {
1217        predicate,
1218        order_by,
1219        limit,
1220        offset: None,
1221    }
1222}
1223
1224fn apply_order_terms_structural(
1225    mut query: StructuralQuery,
1226    order_by: Vec<crate::db::sql::parser::SqlOrderTerm>,
1227) -> StructuralQuery {
1228    for term in order_by {
1229        query = match term.direction {
1230            SqlOrderDirection::Asc => query.order_by(term.field),
1231            SqlOrderDirection::Desc => query.order_by_desc(term.field),
1232        };
1233    }
1234
1235    query
1236}
1237
1238fn normalize_having_clauses(
1239    clauses: Vec<SqlHavingClause>,
1240    entity_scope: &[String],
1241) -> Vec<SqlHavingClause> {
1242    clauses
1243        .into_iter()
1244        .map(|clause| SqlHavingClause {
1245            symbol: normalize_having_symbol(clause.symbol, entity_scope),
1246            op: clause.op,
1247            value: clause.value,
1248        })
1249        .collect()
1250}
1251
1252fn normalize_having_symbol(symbol: SqlHavingSymbol, entity_scope: &[String]) -> SqlHavingSymbol {
1253    match symbol {
1254        SqlHavingSymbol::Field(field) => {
1255            SqlHavingSymbol::Field(normalize_identifier_to_scope(field, entity_scope))
1256        }
1257        SqlHavingSymbol::Aggregate(aggregate) => SqlHavingSymbol::Aggregate(
1258            normalize_aggregate_call_identifiers(aggregate, entity_scope),
1259        ),
1260    }
1261}
1262
1263fn normalize_aggregate_call_identifiers(
1264    aggregate: SqlAggregateCall,
1265    entity_scope: &[String],
1266) -> SqlAggregateCall {
1267    SqlAggregateCall {
1268        kind: aggregate.kind,
1269        field: aggregate
1270            .field
1271            .map(|field| normalize_identifier_to_scope(field, entity_scope)),
1272    }
1273}
1274
1275// Build one identifier scope used for reducing SQL-qualified field references
1276// (`entity.field`, `schema.entity.field`) into canonical planner field names.
1277fn sql_entity_scope_candidates(sql_entity: &str, expected_entity: &'static str) -> Vec<String> {
1278    let mut out = Vec::new();
1279    out.push(sql_entity.to_string());
1280    out.push(expected_entity.to_string());
1281
1282    if let Some(last) = identifier_last_segment(sql_entity) {
1283        out.push(last.to_string());
1284    }
1285    if let Some(last) = identifier_last_segment(expected_entity) {
1286        out.push(last.to_string());
1287    }
1288
1289    out
1290}
1291
1292fn normalize_projection_identifiers(
1293    projection: SqlProjection,
1294    entity_scope: &[String],
1295) -> SqlProjection {
1296    match projection {
1297        SqlProjection::All => SqlProjection::All,
1298        SqlProjection::Items(items) => SqlProjection::Items(
1299            items
1300                .into_iter()
1301                .map(|item| match item {
1302                    SqlSelectItem::Field(field) => {
1303                        SqlSelectItem::Field(normalize_identifier(field, entity_scope))
1304                    }
1305                    SqlSelectItem::Aggregate(aggregate) => {
1306                        SqlSelectItem::Aggregate(SqlAggregateCall {
1307                            kind: aggregate.kind,
1308                            field: aggregate
1309                                .field
1310                                .map(|field| normalize_identifier(field, entity_scope)),
1311                        })
1312                    }
1313                    SqlSelectItem::TextFunction(SqlTextFunctionCall {
1314                        function,
1315                        field,
1316                        literal,
1317                        literal2,
1318                        literal3,
1319                    }) => SqlSelectItem::TextFunction(SqlTextFunctionCall {
1320                        function,
1321                        field: normalize_identifier(field, entity_scope),
1322                        literal,
1323                        literal2,
1324                        literal3,
1325                    }),
1326                })
1327                .collect(),
1328        ),
1329    }
1330}
1331
1332fn normalize_order_terms(
1333    terms: Vec<crate::db::sql::parser::SqlOrderTerm>,
1334    entity_scope: &[String],
1335) -> Vec<crate::db::sql::parser::SqlOrderTerm> {
1336    terms
1337        .into_iter()
1338        .map(|term| crate::db::sql::parser::SqlOrderTerm {
1339            field: normalize_identifier(term.field, entity_scope),
1340            direction: term.direction,
1341        })
1342        .collect()
1343}
1344
1345fn normalize_identifier_list(fields: Vec<String>, entity_scope: &[String]) -> Vec<String> {
1346    fields
1347        .into_iter()
1348        .map(|field| normalize_identifier(field, entity_scope))
1349        .collect()
1350}
1351
1352// SQL lowering only adapts identifier qualification (`entity.field` -> `field`)
1353// and delegates predicate-tree traversal ownership to `db::predicate`.
1354fn adapt_predicate_identifiers_to_scope(
1355    predicate: Predicate,
1356    entity_scope: &[String],
1357) -> Predicate {
1358    rewrite_field_identifiers(predicate, |field| normalize_identifier(field, entity_scope))
1359}
1360
1361fn normalize_identifier(identifier: String, entity_scope: &[String]) -> String {
1362    normalize_identifier_to_scope(identifier, entity_scope)
1363}
1364
1365fn ensure_entity_matches_expected(
1366    sql_entity: &str,
1367    expected_entity: &'static str,
1368) -> Result<(), SqlLoweringError> {
1369    if identifiers_tail_match(sql_entity, expected_entity) {
1370        return Ok(());
1371    }
1372
1373    Err(SqlLoweringError::entity_mismatch(
1374        sql_entity,
1375        expected_entity,
1376    ))
1377}