rigsql_rules/convention/
cv05.rs1use rigsql_core::{Segment, SegmentType, TokenKind};
2
3use crate::rule::{CrawlType, Rule, RuleContext, RuleGroup};
4use crate::violation::{LintViolation, SourceEdit};
5
6#[derive(Debug, Default)]
10pub struct RuleCV05;
11
12impl Rule for RuleCV05 {
13 fn code(&self) -> &'static str {
14 "CV05"
15 }
16 fn name(&self) -> &'static str {
17 "convention.is_null"
18 }
19 fn description(&self) -> &'static str {
20 "Comparisons with NULL should use IS or IS NOT."
21 }
22 fn explanation(&self) -> &'static str {
23 "In SQL, NULL is not a value but the absence of one. Comparison operators \
24 (=, !=, <>) with NULL always return NULL (which is falsy). Use 'IS NULL' or \
25 'IS NOT NULL' instead of '= NULL' or '!= NULL'."
26 }
27 fn groups(&self) -> &[RuleGroup] {
28 &[RuleGroup::Convention]
29 }
30 fn is_fixable(&self) -> bool {
31 true
32 }
33
34 fn crawl_type(&self) -> CrawlType {
35 CrawlType::Segment(vec![SegmentType::BinaryExpression])
36 }
37
38 fn eval(&self, ctx: &RuleContext) -> Vec<LintViolation> {
39 let children = ctx.segment.children();
40
41 let non_trivia: Vec<_> = children
44 .iter()
45 .filter(|c| !c.segment_type().is_trivia())
46 .collect();
47
48 if non_trivia.len() < 3 {
49 return vec![];
50 }
51
52 let op = non_trivia[1];
54 let is_comparison = matches!(op.segment_type(), SegmentType::ComparisonOperator);
55 if !is_comparison {
56 return vec![];
57 }
58
59 let lhs_is_null = is_null_literal(non_trivia[0]);
61 let rhs_is_null = non_trivia.get(2).is_some_and(|s| is_null_literal(s));
62
63 if lhs_is_null || rhs_is_null {
64 let op_text = op.tokens().first().map(|t| t.text.as_str()).unwrap_or("=");
66 let is_negated = op_text == "!=" || op_text == "<>";
67
68 let op_span = op.span();
72 let null_seg = if rhs_is_null {
73 non_trivia[2]
74 } else {
75 non_trivia[0]
76 };
77 let null_span = null_seg.span();
78
79 let fix = if rhs_is_null {
80 let replace_span = rigsql_core::Span::new(op_span.start, null_span.end);
82 let replacement = if is_negated { "IS NOT NULL" } else { "IS NULL" };
83 vec![SourceEdit::replace(replace_span, replacement)]
84 } else {
85 let is_not = if is_negated { "IS NOT NULL" } else { "IS NULL" };
87 let expr = non_trivia[2];
88 let whole_span = ctx.segment.span();
89 let expr_text = ctx
90 .source
91 .get(expr.span().start as usize..expr.span().end as usize)
92 .unwrap_or("?");
93 vec![SourceEdit::replace(
94 whole_span,
95 format!("{} {}", expr_text, is_not),
96 )]
97 };
98
99 return vec![LintViolation::with_fix_and_msg_key(
100 self.code(),
101 "Use IS NULL or IS NOT NULL instead of comparison operator with NULL.",
102 ctx.segment.span(),
103 fix,
104 "rules.CV05.msg",
105 vec![],
106 )];
107 }
108
109 vec![]
110 }
111}
112
113fn is_null_literal(seg: &Segment) -> bool {
114 match seg {
115 Segment::Token(t) => {
116 t.segment_type == SegmentType::NullLiteral
117 || (t.token.kind == TokenKind::Word && t.token.text.eq_ignore_ascii_case("NULL"))
118 }
119 Segment::Node(n) => n.segment_type == SegmentType::NullLiteral,
120 }
121}
122
123#[cfg(test)]
124mod tests {
125 use super::*;
126 use crate::test_utils::lint_sql;
127
128 #[test]
129 fn test_cv05_flags_equals_null() {
130 let violations = lint_sql("SELECT * FROM t WHERE a = NULL", RuleCV05);
131 assert_eq!(violations.len(), 1);
132 assert_eq!(violations[0].fixes.len(), 1);
133 assert_eq!(violations[0].fixes[0].new_text, "IS NULL");
134 }
135
136 #[test]
137 fn test_cv05_accepts_is_null() {
138 let violations = lint_sql("SELECT * FROM t WHERE a IS NULL", RuleCV05);
139 assert_eq!(violations.len(), 0);
140 }
141}