Skip to main content

sqruff_lib_core/parser/segments/
select.rs

1use crate::dialects::common::ColumnAliasInfo;
2use crate::dialects::syntax::{SyntaxKind, SyntaxSet};
3use crate::parser::segments::ErasedSegment;
4
5#[derive(Clone)]
6pub struct SelectClauseElementSegment(pub ErasedSegment);
7
8impl SelectClauseElementSegment {
9    pub fn alias(&self) -> Option<ColumnAliasInfo> {
10        // Stop recursing into nested SELECT statements so that an alias defined
11        // deeper inside a scalar subquery (e.g. `MAX(x.col) AS m`) is not
12        // mistaken for the alias of the outer select clause element
13        // (`(...) AS _stats`). See sqlfluff issue #6389.
14        let alias_expression_segment = self
15            .0
16            .recursive_crawl(
17                const { &SyntaxSet::new(&[SyntaxKind::AliasExpression]) },
18                true,
19                const { &SyntaxSet::new(&[SyntaxKind::SelectStatement]) },
20                true,
21            )
22            .first()?
23            .clone();
24
25        let alias_identifier_segment = alias_expression_segment.segments().iter().find(|it| {
26            matches!(
27                it.get_type(),
28                SyntaxKind::NakedIdentifier | SyntaxKind::Identifier
29            )
30        })?;
31
32        let aliased_segment = self
33            .0
34            .segments()
35            .iter()
36            .find(|&s| !s.is_whitespace() && !s.is_meta() && s != &alias_expression_segment)
37            .unwrap();
38
39        let mut column_reference_segments = Vec::new();
40        if aliased_segment.is_type(SyntaxKind::ColumnReference) {
41            column_reference_segments.push(aliased_segment.clone());
42        } else {
43            column_reference_segments.extend(aliased_segment.recursive_crawl(
44                const { &SyntaxSet::new(&[SyntaxKind::ColumnReference]) },
45                true,
46                &SyntaxSet::EMPTY,
47                true,
48            ));
49        }
50
51        Some(ColumnAliasInfo {
52            alias_identifier_name: alias_identifier_segment.raw().clone(),
53            aliased_segment: aliased_segment.clone(),
54            column_reference_segments,
55        })
56    }
57}