rigsql_rules/ambiguous/
am04.rs1use rigsql_core::{Segment, SegmentType};
2
3use crate::rule::{CrawlType, Rule, RuleContext, RuleGroup};
4use crate::violation::LintViolation;
5
6#[derive(Debug, Default)]
11pub struct RuleAM04;
12
13impl Rule for RuleAM04 {
14 fn code(&self) -> &'static str {
15 "AM04"
16 }
17 fn name(&self) -> &'static str {
18 "ambiguous.column_count"
19 }
20 fn description(&self) -> &'static str {
21 "SELECT * should list columns explicitly."
22 }
23 fn explanation(&self) -> &'static str {
24 "Using SELECT * makes the query's column set depend on the table schema, which \
25 can change over time. Listing columns explicitly makes the query self-documenting \
26 and prevents unexpected changes when columns are added or removed."
27 }
28 fn groups(&self) -> &[RuleGroup] {
29 &[RuleGroup::Ambiguous]
30 }
31 fn is_fixable(&self) -> bool {
32 false
33 }
34
35 fn crawl_type(&self) -> CrawlType {
36 CrawlType::Segment(vec![SegmentType::SelectClause])
37 }
38
39 fn eval(&self, ctx: &RuleContext) -> Vec<LintViolation> {
40 let mut violations = Vec::new();
41 find_bare_stars(ctx.segment, false, &mut violations);
42 violations
43 }
44}
45
46fn find_bare_stars(segment: &Segment, in_function: bool, violations: &mut Vec<LintViolation>) {
48 if segment.segment_type() == SegmentType::Star && !in_function {
49 violations.push(LintViolation::new(
50 "AM04",
51 "SELECT * used. List columns explicitly.",
52 segment.span(),
53 ));
54 return;
55 }
56
57 let entering_function = segment.segment_type() == SegmentType::FunctionCall;
58
59 for child in segment.children() {
60 find_bare_stars(child, in_function || entering_function, violations);
61 }
62}
63
64#[cfg(test)]
65mod tests {
66 use super::*;
67 use crate::test_utils::lint_sql;
68
69 #[test]
70 fn test_am04_flags_select_star() {
71 let violations = lint_sql("SELECT * FROM t", RuleAM04);
72 assert_eq!(violations.len(), 1);
73 }
74
75 #[test]
76 fn test_am04_accepts_explicit_columns() {
77 let violations = lint_sql("SELECT a, b FROM t", RuleAM04);
78 assert_eq!(violations.len(), 0);
79 }
80
81 #[test]
82 fn test_am04_accepts_count_star() {
83 let violations = lint_sql("SELECT COUNT(*) FROM t", RuleAM04);
84 assert_eq!(violations.len(), 0);
85 }
86}