sqruff_lib/rules/convention/
cv01.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
use ahash::AHashMap;
use sqruff_lib_core::dialects::syntax::{SyntaxKind, SyntaxSet};
use sqruff_lib_core::lint_fix::LintFix;
use sqruff_lib_core::parser::segments::base::SegmentBuilder;

use crate::core::config::Value;
use crate::core::rules::base::{Erased, ErasedRule, LintResult, Rule, RuleGroups};
use crate::core::rules::context::RuleContext;
use crate::core::rules::crawlers::{Crawler, SegmentSeekerCrawler};
use crate::utils::functional::context::FunctionalContext;

#[derive(Debug, Default, Clone)]
pub struct RuleCV01 {
    preferred_not_equal_style: PreferredNotEqualStyle,
}

#[derive(Debug, Clone, Copy, PartialEq, Default)]
enum PreferredNotEqualStyle {
    #[default]
    Consistent,
    CStyle,
    Ansi,
}

impl Rule for RuleCV01 {
    fn load_from_config(&self, config: &AHashMap<String, Value>) -> Result<ErasedRule, String> {
        if let Some(value) = config["preferred_not_equal_style"].as_string() {
            let preferred_not_equal_style = match value {
                "consistent" => PreferredNotEqualStyle::Consistent,
                "c_style" => PreferredNotEqualStyle::CStyle,
                "ansi" => PreferredNotEqualStyle::Ansi,
                _ => {
                    return Err(format!(
                        "Invalid value for preferred_not_equal_style: {}",
                        value
                    ))
                }
            };
            Ok(RuleCV01 {
                preferred_not_equal_style,
            }
            .erased())
        } else {
            Err("Missing value for preferred_not_equal_style".to_string())
        }
    }

    fn name(&self) -> &'static str {
        "convention.not_equal"
    }

    fn description(&self) -> &'static str {
        "Consistent usage of ``!=`` or ``<>`` for \"not equal to\" operator."
    }

    fn long_description(&self) -> &'static str {
        r#"
**Anti-pattern**

Consistent usage of `!=` or `<>` for "not equal to" operator.

```sql
SELECT * FROM X WHERE 1 <> 2 AND 3 != 4;
```

**Best practice**

Ensure all "not equal to" comparisons are consistent, not mixing `!=` and `<>`.

```sql
SELECT * FROM X WHERE 1 != 2 AND 3 != 4;
```
"#
    }

    fn groups(&self) -> &'static [RuleGroups] {
        &[RuleGroups::All, RuleGroups::Convention]
    }

    fn eval(&self, context: RuleContext) -> Vec<LintResult> {
        // Get the comparison operator children
        let segment = FunctionalContext::new(context.clone()).segment();
        let raw_comparison_operators = segment.children(None);

        // Only check ``<>`` or ``!=`` operators
        let raw_operator_list = raw_comparison_operators
            .iter()
            .map(|r| r.raw())
            .collect::<Vec<_>>();
        if raw_operator_list != ["<", ">"] && raw_operator_list != ["!", "="] {
            return Vec::new();
        }

        // If style is consistent, add the style of the first occurrence to memory
        let preferred_style =
            if self.preferred_not_equal_style == PreferredNotEqualStyle::Consistent {
                if let Some(preferred_style) = context.try_get::<PreferredNotEqualStyle>() {
                    preferred_style
                } else {
                    let style = if raw_operator_list == ["<", ">"] {
                        PreferredNotEqualStyle::Ansi
                    } else {
                        PreferredNotEqualStyle::CStyle
                    };
                    context.set(style);
                    style
                }
            } else {
                self.preferred_not_equal_style
            };

        // Define the replacement
        let replacement = match preferred_style {
            PreferredNotEqualStyle::CStyle => {
                vec!["!", "="]
            }
            PreferredNotEqualStyle::Ansi => {
                vec!["<", ">"]
            }
            PreferredNotEqualStyle::Consistent => {
                unreachable!("Consistent style should have been handled earlier")
            }
        };

        // This operator already matches the existing style
        if raw_operator_list == replacement {
            return Vec::new();
        }

        // Provide a fix and replace ``<>`` with ``!=``
        // As each symbol is a separate symbol this is done in two steps:
        // Depending on style type, flip any inconsistent operators
        // 1. Flip < and !
        // 2. Flip > and =
        let fixes = vec![
            LintFix::replace(
                raw_comparison_operators[0].clone(),
                vec![SegmentBuilder::token(
                    context.tables.next_id(),
                    replacement[0],
                    SyntaxKind::ComparisonOperator,
                )
                .finish()],
                None,
            ),
            LintFix::replace(
                raw_comparison_operators[1].clone(),
                vec![SegmentBuilder::token(
                    context.tables.next_id(),
                    replacement[1],
                    SyntaxKind::ComparisonOperator,
                )
                .finish()],
                None,
            ),
        ];

        vec![LintResult::new(
            context.segment.clone().into(),
            fixes,
            None,
            None,
            None,
        )]
    }

    fn is_fix_compatible(&self) -> bool {
        true
    }

    fn crawl_behaviour(&self) -> Crawler {
        SegmentSeekerCrawler::new(const { SyntaxSet::new(&[SyntaxKind::ComparisonOperator]) })
            .into()
    }
}