Skip to main content

rigsql_rules/convention/
cv12.rs

1use rigsql_core::SegmentType;
2
3use crate::rule::{CrawlType, Rule, RuleContext, RuleGroup};
4use crate::violation::LintViolation;
5
6/// CV12: Use of HAVING without GROUP BY.
7///
8/// A HAVING clause without a corresponding GROUP BY is likely a mistake;
9/// use WHERE instead, or add the missing GROUP BY.
10#[derive(Debug, Default)]
11pub struct RuleCV12;
12
13impl Rule for RuleCV12 {
14    fn code(&self) -> &'static str {
15        "CV12"
16    }
17    fn name(&self) -> &'static str {
18        "convention.having_without_group_by"
19    }
20    fn description(&self) -> &'static str {
21        "Use of HAVING without GROUP BY."
22    }
23    fn explanation(&self) -> &'static str {
24        "HAVING is designed to filter grouped results. Using HAVING without GROUP BY \
25         treats the entire result set as a single group, which is almost always a mistake. \
26         Use WHERE for filtering ungrouped rows, or add the missing GROUP BY clause."
27    }
28    fn groups(&self) -> &[RuleGroup] {
29        &[RuleGroup::Convention]
30    }
31    fn is_fixable(&self) -> bool {
32        false
33    }
34
35    fn crawl_type(&self) -> CrawlType {
36        CrawlType::Segment(vec![SegmentType::SelectStatement])
37    }
38
39    fn eval(&self, ctx: &RuleContext) -> Vec<LintViolation> {
40        let children = ctx.segment.children();
41
42        let has_having = children
43            .iter()
44            .any(|c| c.segment_type() == SegmentType::HavingClause);
45        let has_group_by = children
46            .iter()
47            .any(|c| c.segment_type() == SegmentType::GroupByClause);
48
49        if has_having && !has_group_by {
50            // Find the HavingClause span to report on
51            let having_span = children
52                .iter()
53                .find(|c| c.segment_type() == SegmentType::HavingClause)
54                .map(|c| c.span())
55                .unwrap_or(ctx.segment.span());
56
57            return vec![LintViolation::new(
58                self.code(),
59                "HAVING clause without GROUP BY. Use WHERE for ungrouped filtering.",
60                having_span,
61            )];
62        }
63
64        vec![]
65    }
66}