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

use crate::core::config::Value;
use crate::core::parser::segments::base::SegmentBuilder;
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};

/// Prefer using `COALESCE` over `IFNULL` or `NVL`.
///
/// # Anti-pattern
///
/// `IFNULL` or `NVL` are commonly used to handle `NULL` values in SQL queries.
/// However, they have compatibility issues across different database systems.
///
/// ```sql
/// SELECT ifnull(foo, 0) AS bar,
/// FROM baz;
///
/// SELECT nvl(foo, 0) AS bar,
/// FROM baz;
/// ```
///
/// # Best Practice
///
/// It is recommended to use `COALESCE` instead. `COALESCE` is universally
/// supported, while `IFNULL` is not supported in Redshift, and `NVL` is not
/// supported in BigQuery. Moreover, `COALESCE` offers greater flexibility, as
/// it can accept an arbitrary number of arguments, enhancing the query's
/// robustness.
///
/// ```sql
/// SELECT coalesce(foo, 0) AS bar,
/// FROM baz;
/// ```
#[derive(Debug, Default, Clone)]
pub struct RuleCV02;

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

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

    fn description(&self) -> &'static str {
        "Use 'COALESCE' instead of 'IFNULL' or 'NVL'."
    }

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

`IFNULL` or `NVL` are used to fill `NULL` values.

```sql
SELECT ifnull(foo, 0) AS bar,
FROM baz;

SELECT nvl(foo, 0) AS bar,
FROM baz;
```

**Best practice**

Use COALESCE instead. COALESCE is universally supported, whereas Redshift doesn’t support IFNULL and BigQuery doesn’t support NVL. Additionally, COALESCE is more flexible and accepts an arbitrary number of arguments.

```sql
SELECT coalesce(foo, 0) AS bar,
FROM baz;
```
"#
    }

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

    fn eval(&self, context: RuleContext) -> Vec<LintResult> {
        // Use "COALESCE" instead of "IFNULL" or "NVL".
        // We only care about function names, and they should be the
        // only things we get.
        // assert!(context.segment.is_type(SyntaxKind::FunctionNameIdentifier));

        // Only care if the function is "IFNULL" or "NVL".

        if !["IFNULL", "NVL"].contains(&context.segment.get_raw_upper().unwrap().as_str()) {
            return Vec::new();
        }

        // Create fix to replace "IFNULL" or "NVL" with "COALESCE".
        let fix = LintFix::replace(
            context.segment.clone(),
            vec![
                SegmentBuilder::token(
                    context.tables.next_id(),
                    "COALESCE",
                    SyntaxKind::FunctionNameIdentifier,
                )
                .finish(),
            ],
            None,
        );

        vec![LintResult::new(
            context.segment.clone().into(),
            vec![fix],
            None,
            Some(format!(
                "Use 'COALESCE' instead of '{}'.",
                context.segment.get_raw_upper().unwrap()
            )),
            None,
        )]
    }

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

#[cfg(test)]
mod tests {
    use crate::api::simple::{fix, lint};
    use crate::core::dialects::init::get_default_dialect;
    use crate::core::rules::base::Erased;
    use crate::rules::convention::cv02::RuleCV02;

    #[test]
    fn test_rules_std_cv02_raised() {
        // CV02 is raised for use of "IFNULL" or "NVL".
        let sql = "SELECT\n\tIFNULL(NULL, 100),\n\tNVL(NULL, 100);";
        let result = lint(
            sql.into(),
            get_default_dialect().to_string(),
            vec![RuleCV02.erased()],
            None,
            None,
        )
        .unwrap();

        assert_eq!(result.len(), 2);
        assert_eq!(result[0].description, "Use 'COALESCE' instead of 'IFNULL'.");
        assert_eq!(result[1].description, "Use 'COALESCE' instead of 'NVL'.");
    }

    #[test]
    fn test_pass_coalesce() {
        let sql = "SELECT coalesce(foo, 0) AS bar,\nFROM baz;";

        let result = lint(
            sql.into(),
            get_default_dialect().to_string(),
            vec![RuleCV02.erased()],
            None,
            None,
        )
        .unwrap();

        assert!(result.is_empty());
    }

    #[test]
    fn test_fail_ifnull() {
        let sql = "SELECT ifnull(foo, 0) AS bar,\nFROM baz;";
        let result = fix(sql, vec![RuleCV02.erased()]);
        assert_eq!(result, "SELECT COALESCE(foo, 0) AS bar,\nFROM baz;")
    }

    #[test]
    fn test_fail_nvl() {
        let sql = "SELECT nvl(foo, 0) AS bar,\nFROM baz;";
        let result = fix(sql, vec![RuleCV02.erased()]);
        assert_eq!(result, "SELECT COALESCE(foo, 0) AS bar,\nFROM baz;")
    }
}