sqruff_lib/rules/structure/
st02.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
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
use ahash::{AHashMap, AHashSet};
use itertools::{chain, Itertools};
use smol_str::StrExt;
use sqruff_lib_core::dialects::syntax::{SyntaxKind, SyntaxSet};
use sqruff_lib_core::lint_fix::LintFix;
use sqruff_lib_core::parser::segments::base::{ErasedSegment, SegmentBuilder};
use sqruff_lib_core::utils::functional::segments::Segments;

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(Default, Debug, Clone)]
pub struct RuleST02;

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

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

    fn description(&self) -> &'static str {
        "Unnecessary 'CASE' statement."
    }

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

CASE statement returns booleans.

```sql
select
    case
        when fab > 0 then true
        else false
    end as is_fab
from fancy_table

-- This rule can also simplify CASE statements
-- that aim to fill NULL values.

select
    case
        when fab is null then 0
        else fab
    end as fab_clean
from fancy_table

-- This also covers where the case statement
-- replaces NULL values with NULL values.

select
    case
        when fab is null then null
        else fab
    end as fab_clean
from fancy_table
```

**Best practice**

Reduce to WHEN condition within COALESCE function.

```sql
select
    coalesce(fab > 0, false) as is_fab
from fancy_table

-- To fill NULL values.

select
    coalesce(fab, 0) as fab_clean
from fancy_table

-- NULL filling NULL.

select fab as fab_clean
from fancy_table
```
"#
    }

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

    fn eval(&self, context: RuleContext) -> Vec<LintResult> {
        if context.segment.segments()[0]
            .raw()
            .eq_ignore_ascii_case("CASE")
        {
            let children = FunctionalContext::new(context.clone())
                .segment()
                .children(None);

            let when_clauses = children.select(
                Some(|it: &ErasedSegment| it.is_type(SyntaxKind::WhenClause)),
                None,
                None,
                None,
            );
            let else_clauses = children.select(
                Some(|it: &ErasedSegment| it.is_type(SyntaxKind::ElseClause)),
                None,
                None,
                None,
            );

            if when_clauses.len() > 1 {
                return Vec::new();
            }

            let condition_expression =
                when_clauses.children(Some(|it| it.is_type(SyntaxKind::Expression)))[0].clone();
            let then_expression =
                when_clauses.children(Some(|it| it.is_type(SyntaxKind::Expression)))[1].clone();

            if !else_clauses.is_empty() {
                if let Some(else_expression) = else_clauses
                    .children(Some(|it| it.is_type(SyntaxKind::Expression)))
                    .first()
                {
                    let upper_bools = ["TRUE", "FALSE"];

                    let then_expression_upper = then_expression.raw().to_uppercase_smolstr();
                    let else_expression_upper = else_expression.raw().to_uppercase_smolstr();

                    if upper_bools.contains(&then_expression_upper.as_str())
                        && upper_bools.contains(&else_expression_upper.as_str())
                        && then_expression_upper != else_expression_upper
                    {
                        let coalesce_arg_1 = condition_expression.clone();
                        let coalesce_arg_2 =
                            SegmentBuilder::keyword(context.tables.next_id(), "false");
                        let preceding_not = then_expression_upper == "FALSE";

                        let fixes = Self::coalesce_fix_list(
                            &context,
                            coalesce_arg_1,
                            coalesce_arg_2,
                            preceding_not,
                        );

                        return vec![LintResult::new(
                            condition_expression.into(),
                            fixes,
                            None,
                            "Unnecessary CASE statement. Use COALESCE function instead."
                                .to_owned()
                                .into(),
                            None,
                        )];
                    }
                }
            }

            let condition_expression_segments_raw: AHashSet<_> = AHashSet::from_iter(
                condition_expression
                    .segments()
                    .iter()
                    .map(|segment| segment.raw().to_uppercase_smolstr()),
            );

            if condition_expression_segments_raw.contains("IS")
                && condition_expression_segments_raw.contains("NULL")
                && condition_expression_segments_raw
                    .intersection(&AHashSet::from_iter(["AND".into(), "OR".into()]))
                    .next()
                    .is_none()
            {
                let is_not_prefix = condition_expression_segments_raw.contains("NOT");

                let tmp = Segments::new(condition_expression.clone(), None)
                    .children(Some(|it| it.is_type(SyntaxKind::ColumnReference)));

                let Some(column_reference_segment) = tmp.first() else {
                    return Vec::new();
                };

                let array_accessor_segment = Segments::new(condition_expression.clone(), None)
                    .children(Some(|it: &ErasedSegment| {
                        it.is_type(SyntaxKind::ArrayAccessor)
                    }))
                    .first()
                    .cloned();

                let column_reference_segment_raw_upper = match array_accessor_segment {
                    Some(array_accessor_segment) => {
                        column_reference_segment.raw().to_lowercase()
                            + &array_accessor_segment.raw().to_uppercase()
                    }
                    None => column_reference_segment.raw().to_uppercase(),
                };

                if !else_clauses.is_empty() {
                    let else_expression = else_clauses
                        .children(Some(|it| it.is_type(SyntaxKind::Expression)))[0]
                        .clone();

                    let (coalesce_arg_1, coalesce_arg_2) = if !is_not_prefix
                        && column_reference_segment_raw_upper
                            == else_expression.raw().to_uppercase_smolstr()
                    {
                        (else_expression, then_expression)
                    } else if is_not_prefix
                        && column_reference_segment_raw_upper
                            == then_expression.raw().to_uppercase_smolstr()
                    {
                        (then_expression, else_expression)
                    } else {
                        return Vec::new();
                    };

                    if coalesce_arg_2.raw().eq_ignore_ascii_case("NULL") {
                        let fixes =
                            Self::column_only_fix_list(&context, column_reference_segment.clone());
                        return vec![LintResult::new(
                            condition_expression.into(),
                            fixes,
                            None,
                            Some(String::new()),
                            None,
                        )];
                    }

                    let fixes =
                        Self::coalesce_fix_list(&context, coalesce_arg_1, coalesce_arg_2, false);

                    return vec![LintResult::new(
                        condition_expression.into(),
                        fixes,
                        None,
                        "Unnecessary CASE statement. Use COALESCE function instead."
                            .to_owned()
                            .into(),
                        None,
                    )];
                } else if column_reference_segment
                    .raw()
                    .eq_ignore_ascii_case(then_expression.raw())
                {
                    let fixes =
                        Self::column_only_fix_list(&context, column_reference_segment.clone());

                    return vec![LintResult::new(
                        condition_expression.into(),
                        fixes,
                        None,
                        format!(
                            "Unnecessary CASE statement. Just use column '{}'.",
                            column_reference_segment.raw()
                        )
                        .into(),
                        None,
                    )];
                }
            }

            Vec::new()
        } else {
            Vec::new()
        }
    }

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

impl RuleST02 {
    fn coalesce_fix_list(
        context: &RuleContext,
        coalesce_arg_1: ErasedSegment,
        coalesce_arg_2: ErasedSegment,
        preceding_not: bool,
    ) -> Vec<LintFix> {
        let mut edits = vec![
            SegmentBuilder::token(
                context.tables.next_id(),
                "coalesce",
                SyntaxKind::FunctionNameIdentifier,
            )
            .finish(),
            SegmentBuilder::symbol(context.tables.next_id(), "("),
            coalesce_arg_1,
            SegmentBuilder::symbol(context.tables.next_id(), ","),
            SegmentBuilder::whitespace(context.tables.next_id(), " "),
            coalesce_arg_2,
            SegmentBuilder::symbol(context.tables.next_id(), ")"),
        ];

        if preceding_not {
            edits = chain(
                [
                    SegmentBuilder::keyword(context.tables.next_id(), "not"),
                    SegmentBuilder::whitespace(context.tables.next_id(), " "),
                ],
                edits,
            )
            .collect_vec();
        }

        vec![LintFix::replace(context.segment.clone(), edits, None)]
    }

    fn column_only_fix_list(
        context: &RuleContext,
        column_reference_segment: ErasedSegment,
    ) -> Vec<LintFix> {
        vec![LintFix::replace(
            context.segment.clone(),
            vec![column_reference_segment],
            None,
        )]
    }
}