rigsql_rules/aliasing/
al04.rs1use std::collections::HashMap;
2
3use rigsql_core::{Segment, SegmentType};
4
5use crate::rule::{CrawlType, Rule, RuleContext, RuleGroup};
6use crate::utils::extract_alias_name;
7use crate::violation::LintViolation;
8
9#[derive(Debug, Default)]
13pub struct RuleAL04;
14
15impl Rule for RuleAL04 {
16 fn code(&self) -> &'static str {
17 "AL04"
18 }
19 fn name(&self) -> &'static str {
20 "aliasing.unique_table"
21 }
22 fn description(&self) -> &'static str {
23 "Table aliases should be unique within a statement."
24 }
25 fn explanation(&self) -> &'static str {
26 "When the same alias is used for multiple tables in a single statement, \
27 column references become ambiguous. Each table alias must be unique within \
28 its containing statement."
29 }
30 fn groups(&self) -> &[RuleGroup] {
31 &[RuleGroup::Aliasing]
32 }
33 fn is_fixable(&self) -> bool {
34 false
35 }
36
37 fn crawl_type(&self) -> CrawlType {
38 CrawlType::Segment(vec![SegmentType::SelectStatement])
39 }
40
41 fn eval(&self, ctx: &RuleContext) -> Vec<LintViolation> {
42 let mut aliases: Vec<(String, rigsql_core::Span)> = Vec::new();
43 collect_table_aliases(ctx.segment, &mut aliases);
44
45 let mut violations = Vec::new();
46 let mut seen: HashMap<String, rigsql_core::Span> = HashMap::new();
47
48 for (name, span) in &aliases {
49 let lower = name.to_lowercase();
50 if let Some(first_span) = seen.get(&lower) {
51 violations.push(LintViolation::new(
52 self.code(),
53 format!(
54 "Duplicate table alias '{}'. First used at offset {}.",
55 name, first_span.start,
56 ),
57 *span,
58 ));
59 } else {
60 seen.insert(lower, *span);
61 }
62 }
63
64 violations
65 }
66}
67
68fn collect_table_aliases(segment: &Segment, aliases: &mut Vec<(String, rigsql_core::Span)>) {
70 let st = segment.segment_type();
71
72 if st == SegmentType::FromClause || st == SegmentType::JoinClause {
74 find_alias_names(segment, aliases);
75 return;
76 }
77
78 if st == SegmentType::SelectStatement || st == SegmentType::Subquery {
80 if st == SegmentType::Subquery {
83 return;
84 }
85 }
86
87 for child in segment.children() {
88 collect_table_aliases(child, aliases);
89 }
90}
91
92fn find_alias_names(segment: &Segment, aliases: &mut Vec<(String, rigsql_core::Span)>) {
94 if segment.segment_type() == SegmentType::AliasExpression {
95 if let Some(name) = extract_alias_name(segment.children()) {
96 aliases.push((name, segment.span()));
97 }
98 return;
99 }
100
101 if segment.segment_type() == SegmentType::Subquery {
103 return;
104 }
105
106 for child in segment.children() {
107 find_alias_names(child, aliases);
108 }
109}