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
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};
use crate::core::rules::context::RuleContext;
use crate::core::rules::crawlers::{Crawler, SegmentSeekerCrawler};
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>) -> ErasedRule {
        RuleST01::default().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 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("else_clause")));

        if !else_clause
            .children(Some(|child| child.get_raw().unwrap().eq_ignore_ascii_case("NULL")))
            .is_empty()
        {
            let before_else = children.reversed().select(
                None,
                Some(|it| matches!(it.get_type(), "whitespace" | "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_box()));
            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(["case_expression"].into()).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::default().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.into(), 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.into(), 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.into(), 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.into(), rules());
        assert_eq!(pass_str, fixed);
    }
}