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
176
use ahash::AHashMap;

use crate::core::config::Value;
use crate::core::parser::segments::base::ErasedSegment;
use crate::core::rules::base::{Erased, ErasedRule, LintFix, LintResult, Rule, RuleGroups};
use crate::core::rules::context::RuleContext;
use crate::core::rules::crawlers::{Crawler, SegmentSeekerCrawler};
use crate::dialects::{SyntaxKind, SyntaxSet};
use crate::utils::functional::context::FunctionalContext;

#[derive(Default, Debug, Clone)]
pub struct RuleST01;

impl Rule for RuleST01 {
    fn load_from_config(&self, _config: &AHashMap<String, Value>) -> Result<ErasedRule, String> {
        Ok(RuleST01.erased())
    }

    fn name(&self) -> &'static str {
        "structure.else_null"
    }

    fn description(&self) -> &'static str {
        "Do not specify 'else null' in a case when statement (redundant)."
    }

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

In this example, the reference `vee` has not been declared.

```sql
SELECT
    vee.a
FROM foo
```

**Best practice**

Remove the reference.

```sql
SELECT
    a
FROM foo
```
"#
    }

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

    fn eval(&self, context: RuleContext) -> Vec<LintResult> {
        let anchor = context.segment.clone();

        let children = FunctionalContext::new(context).segment().children(None);
        let else_clause =
            children.find_first(Some(|it: &ErasedSegment| it.is_type(SyntaxKind::ElseClause)));

        if !else_clause.children(Some(|child| child.raw().eq_ignore_ascii_case("NULL"))).is_empty()
        {
            let before_else = children.reversed().select::<fn(&ErasedSegment) -> bool>(
                None,
                Some(|it| {
                    matches!(it.get_type(), SyntaxKind::Whitespace | SyntaxKind::Newline)
                        | it.is_meta()
                }),
                else_clause.first().unwrap().into(),
                None,
            );

            let mut fixes = Vec::with_capacity(before_else.len() + 1);
            fixes.push(LintFix::delete(else_clause.first().unwrap().clone()));
            fixes.extend(before_else.into_iter().map(LintFix::delete));

            vec![LintResult::new(anchor.into(), fixes, None, None, None)]
        } else {
            Vec::new()
        }
    }

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

#[cfg(test)]
mod tests {
    use pretty_assertions::assert_eq;

    use crate::api::simple::fix;
    use crate::core::rules::base::{Erased, ErasedRule};
    use crate::rules::structure::ST01::RuleST01;

    fn rules() -> Vec<ErasedRule> {
        vec![RuleST01.erased()]
    }

    #[test]
    fn redundant_else_null() {
        let fail_str = "
    select
        case name
            when 'cat' then 'meow'
            when 'dog' then 'woof'
            else null
        end
    from x";

        let fix_str = "
    select
        case name
            when 'cat' then 'meow'
            when 'dog' then 'woof'
        end
    from x";

        let fixed = fix(fail_str, rules());
        assert_eq!(fix_str, fixed);
    }

    #[test]
    fn alternate_case_when_syntax() {
        let fail_str = "
    select
        case name
            when 'cat' then 'meow'
            when 'dog' then 'woof'
            else null
        end
    from x";

        let fix_str = "
    select
        case name
            when 'cat' then 'meow'
            when 'dog' then 'woof'
        end
    from x";

        let fixed = fix(fail_str, rules());
        assert_eq!(fix_str, fixed);
    }

    #[test]
    fn alternate_case_when_syntax_boolean() {
        let pass_str = "
    select
        case name
            when 'cat' then true
            when 'dog' then true
            else name is null
        end
    from x";

        let fixed = fix(pass_str, rules());
        assert_eq!(pass_str, fixed);
    }

    #[test]
    fn else_expression() {
        let pass_str = "
    select
        case name
            when 'cat' then 'meow'
            when 'dog' then 'woof'
            else iff(wing_type is not null, 'tweet', 'invalid')
        end
    from x";

        let fixed = fix(pass_str, rules());
        assert_eq!(pass_str, fixed);
    }
}