rigsql-rules 0.7.1

Lint rules (sqlfluff-compatible) for the rigsql SQL linter
Documentation
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
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
use rigsql_core::{Segment, SegmentType, TokenKind};

use super::CapitalisationPolicy;
use crate::rule::{CrawlType, Rule, RuleContext, RuleGroup};
use crate::utils::{check_capitalisation, determine_majority_case};
use crate::violation::LintViolation;

/// Built-in SQL function names (sorted alphabetically for binary_search).
const BUILTIN_FUNCTIONS: &[&str] = &[
    "ABS",
    "ACOS",
    "APP_NAME",
    "ASCII",
    "ASIN",
    "ATAN",
    "ATAN2",
    "AVG",
    "CAST",
    "CEILING",
    "CHAR",
    "CHARINDEX",
    "CHOOSE",
    "COALESCE",
    "CONCAT",
    "CONCAT_WS",
    "CONVERT",
    "COS",
    "COT",
    "COUNT",
    "COUNT_BIG",
    "CUME_DIST",
    "CURRENT_TIMESTAMP",
    "CURRENT_USER",
    "CURSOR_STATUS",
    "DATALENGTH",
    "DATEADD",
    "DATEDIFF",
    "DATEDIFF_BIG",
    "DATEFROMPARTS",
    "DATENAME",
    "DATEPART",
    "DATETIME2FROMPARTS",
    "DATETIMEFROMPARTS",
    "DAY",
    "DB_ID",
    "DB_NAME",
    "DENSE_RANK",
    "DIFFERENCE",
    "EOMONTH",
    "ERROR_LINE",
    "ERROR_MESSAGE",
    "ERROR_NUMBER",
    "ERROR_PROCEDURE",
    "ERROR_SEVERITY",
    "ERROR_STATE",
    "EXP",
    "FIRST_VALUE",
    "FLOOR",
    "FORMAT",
    "GETDATE",
    "GETUTCDATE",
    "GREATEST",
    "GROUPING",
    "GROUPING_ID",
    "HAS_PERMS_BY_NAME",
    "HOST_NAME",
    "IDENTITY",
    "IDENT_CURRENT",
    "IFNULL",
    "IIF",
    "ISJSON",
    "ISNULL",
    "ISNUMERIC",
    "JSON_ARRAY",
    "JSON_MODIFY",
    "JSON_OBJECT",
    "JSON_QUERY",
    "JSON_VALUE",
    "LAG",
    "LAST_VALUE",
    "LEAD",
    "LEAST",
    "LEFT",
    "LEN",
    "LENGTH",
    "LOG",
    "LOG10",
    "LOWER",
    "LTRIM",
    "MAX",
    "MIN",
    "MONTH",
    "NCHAR",
    "NEWID",
    "NTILE",
    "NULLIF",
    "NVL",
    "NVL2",
    "OBJECT_ID",
    "OBJECT_NAME",
    "PARSENAME",
    "PATINDEX",
    "PERCENT_RANK",
    "PI",
    "POWER",
    "QUOTENAME",
    "RAND",
    "RANK",
    "REPLACE",
    "REPLICATE",
    "REVERSE",
    "RIGHT",
    "ROUND",
    "ROW_NUMBER",
    "RTRIM",
    "SCHEMA_NAME",
    "SCOPE_IDENTITY",
    "SIGN",
    "SIN",
    "SOUNDEX",
    "SPACE",
    "SQRT",
    "SQUARE",
    "STR",
    "STRING_AGG",
    "STRING_SPLIT",
    "STUFF",
    "SUBSTRING",
    "SUM",
    "SUSER_SNAME",
    "SWITCHOFFSET",
    "SYSDATETIME",
    "SYSUTCDATETIME",
    "TAN",
    "TODATETIMEOFFSET",
    "TRANSLATE",
    "TRIM",
    "TRY_CAST",
    "TRY_CONVERT",
    "TRY_PARSE",
    "TYPE_NAME",
    "UNICODE",
    "UPPER",
    "USER_NAME",
    "YEAR",
];

/// CP03: Function names must be consistently capitalised.
///
/// By default, expects UPPER case function names (sqlfluff-compatible).
#[derive(Debug)]
pub struct RuleCP03 {
    pub policy: CapitalisationPolicy,
}

impl Default for RuleCP03 {
    fn default() -> Self {
        Self {
            policy: CapitalisationPolicy::Upper,
        }
    }
}

impl Rule for RuleCP03 {
    fn code(&self) -> &'static str {
        "CP03"
    }
    fn name(&self) -> &'static str {
        "capitalisation.functions"
    }
    fn description(&self) -> &'static str {
        "Function names must be consistently capitalised."
    }
    fn explanation(&self) -> &'static str {
        "Function names like COUNT, SUM, COALESCE should be consistently capitalised. \
         Whether upper or lower depends on your team's convention."
    }
    fn groups(&self) -> &[RuleGroup] {
        &[RuleGroup::Capitalisation]
    }
    fn is_fixable(&self) -> bool {
        true
    }

    fn crawl_type(&self) -> CrawlType {
        if self.policy == CapitalisationPolicy::Consistent {
            CrawlType::RootOnly
        } else {
            CrawlType::Segment(vec![SegmentType::FunctionCall])
        }
    }

    fn configure(&mut self, settings: &std::collections::HashMap<String, String>) {
        if let Some(policy) = settings.get("capitalisation_policy") {
            self.policy = CapitalisationPolicy::from_config(policy);
        }
    }

    fn eval(&self, ctx: &RuleContext) -> Vec<LintViolation> {
        if self.policy == CapitalisationPolicy::Consistent {
            return self.eval_consistent(ctx);
        }

        // FunctionCall's first child should be the function name (Identifier)
        let children = ctx.segment.children();
        if children.is_empty() {
            return vec![];
        }

        // Walk to find the function name token
        let name_seg = Self::find_function_name(children);
        let Some(Segment::Token(t)) = name_seg else {
            return vec![];
        };
        if t.token.kind != TokenKind::Word {
            return vec![];
        }

        let text = t.token.text.as_str();
        let upper = text.to_ascii_uppercase();

        // Only check built-in SQL functions; skip user-defined functions
        if BUILTIN_FUNCTIONS.binary_search(&upper.as_str()).is_err() {
            return vec![];
        }

        let (expected, policy_name) = match self.policy {
            CapitalisationPolicy::Upper => (upper, "upper"),
            CapitalisationPolicy::Lower => (text.to_ascii_lowercase(), "lower"),
            CapitalisationPolicy::Capitalise => (crate::utils::capitalise(text), "capitalised"),
            CapitalisationPolicy::Consistent => unreachable!(),
        };

        check_capitalisation(
            self.code(),
            "Function names",
            text,
            &expected,
            policy_name,
            t.token.span,
        )
        .into_iter()
        .collect()
    }
}

impl RuleCP03 {
    fn eval_consistent(&self, ctx: &RuleContext) -> Vec<LintViolation> {
        let mut tokens = Vec::new();
        Self::collect_builtin_function_names(ctx.root, &mut tokens);

        if tokens.is_empty() {
            return vec![];
        }

        let majority = determine_majority_case(&tokens);
        let mut violations = Vec::new();
        for (text, span) in &tokens {
            let expected = match majority {
                "upper" => text.to_ascii_uppercase(),
                _ => text.to_ascii_lowercase(),
            };
            if let Some(v) = check_capitalisation(
                self.code(),
                "Function names",
                text,
                &expected,
                majority,
                *span,
            ) {
                violations.push(v);
            }
        }
        violations
    }

    /// Recursively collect built-in function name tokens from the CST.
    fn collect_builtin_function_names(
        segment: &Segment,
        out: &mut Vec<(String, rigsql_core::Span)>,
    ) {
        if segment.segment_type() == SegmentType::FunctionCall {
            if let Some(Segment::Token(t)) = Self::find_function_name(segment.children()) {
                if t.token.kind == TokenKind::Word {
                    let upper = t.token.text.to_ascii_uppercase();
                    if BUILTIN_FUNCTIONS.binary_search(&upper.as_str()).is_ok() {
                        out.push((t.token.text.to_string(), t.token.span));
                    }
                }
            }
        }
        for child in segment.children() {
            Self::collect_builtin_function_names(child, out);
        }
    }

    fn find_function_name(children: &[Segment]) -> Option<&Segment> {
        for child in children {
            match child.segment_type() {
                SegmentType::Identifier => return Some(child),
                SegmentType::ColumnRef => {
                    // qualified function: schema.func — get last identifier
                    let inner = child.children();
                    return inner
                        .iter()
                        .rev()
                        .find(|s| s.segment_type() == SegmentType::Identifier);
                }
                _ if child.segment_type().is_trivia() => continue,
                _ => break,
            }
        }
        None
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::test_utils::lint_sql;

    #[test]
    fn test_cp03_flags_lowercase_function() {
        // Default policy is upper, so lowercase should be flagged
        let violations = lint_sql("SELECT count(*) FROM t", RuleCP03::default());
        assert_eq!(violations.len(), 1);
        assert_eq!(violations[0].fixes[0].new_text, "COUNT");
    }

    #[test]
    fn test_cp03_flags_mixed_case() {
        let violations = lint_sql("SELECT Count(*) FROM t", RuleCP03::default());
        assert_eq!(violations.len(), 1);
        assert_eq!(violations[0].fixes[0].new_text, "COUNT");
    }

    #[test]
    fn test_cp03_accepts_all_upper() {
        let violations = lint_sql("SELECT COUNT(*) FROM t", RuleCP03::default());
        assert_eq!(violations.len(), 0);
    }

    #[test]
    fn test_cp03_lower_policy_flags_upper() {
        let rule = RuleCP03 {
            policy: CapitalisationPolicy::Lower,
        };
        let violations = lint_sql("SELECT COUNT(*) FROM t", rule);
        assert_eq!(violations.len(), 1);
        assert_eq!(violations[0].fixes[0].new_text, "count");
    }

    #[test]
    fn test_cp03_lower_policy_accepts_lower() {
        let rule = RuleCP03 {
            policy: CapitalisationPolicy::Lower,
        };
        let violations = lint_sql("SELECT count(*) FROM t", rule);
        assert_eq!(violations.len(), 0);
    }

    #[test]
    fn test_cp03_capitalise_policy() {
        let rule = RuleCP03 {
            policy: CapitalisationPolicy::Capitalise,
        };
        let violations = lint_sql("SELECT count(*) FROM t", rule);
        assert_eq!(violations.len(), 1);
        assert_eq!(violations[0].fixes[0].new_text, "Count");
    }

    #[test]
    fn test_cp03_skips_user_defined_function() {
        let violations = lint_sql(
            "SELECT GetDropdownOptions('a', 'b') FROM t",
            RuleCP03::default(),
        );
        assert_eq!(violations.len(), 0);
    }

    #[test]
    fn test_cp03_consistent_flags_minority() {
        // 2 upper (COUNT, SUM) vs 1 lower (avg) → majority upper, flag "avg"
        let rule = RuleCP03 {
            policy: CapitalisationPolicy::Consistent,
        };
        let violations = lint_sql("SELECT COUNT(*), SUM(x), avg(y) FROM t", rule);
        assert_eq!(violations.len(), 1);
        assert_eq!(violations[0].fixes[0].new_text, "AVG");
    }

    #[test]
    fn test_cp03_consistent_all_same_no_violation() {
        let rule = RuleCP03 {
            policy: CapitalisationPolicy::Consistent,
        };
        let violations = lint_sql("SELECT COUNT(*), SUM(x) FROM t", rule);
        assert_eq!(violations.len(), 0);
    }

    #[test]
    fn test_cp03_consistent_majority_lower() {
        // 2 lower (count, sum) vs 1 upper (AVG) → majority lower, flag "AVG"
        let rule = RuleCP03 {
            policy: CapitalisationPolicy::Consistent,
        };
        let violations = lint_sql("SELECT count(*), sum(x), AVG(y) FROM t", rule);
        assert_eq!(violations.len(), 1);
        assert_eq!(violations[0].fixes[0].new_text, "avg");
    }

    #[test]
    fn test_cp03_flags_replace_function() {
        // The issue from #32: replace should be flagged and fixed to REPLACE
        let violations = lint_sql("SELECT replace(col, 'a', 'b') FROM t", RuleCP03::default());
        assert_eq!(violations.len(), 1);
        assert_eq!(violations[0].fixes[0].new_text, "REPLACE");
    }
}