sqruff_lib/rules/convention/
cv11.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
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
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
use ahash::AHashMap;
use itertools::chain;
use sqruff_lib_core::dialects::syntax::{SyntaxKind, SyntaxSet};
use sqruff_lib_core::lint_fix::LintFix;
use sqruff_lib_core::parser::segments::base::{ErasedSegment, SegmentBuilder, Tables};
use sqruff_lib_core::utils::functional::segments::Segments;
use strum_macros::{AsRefStr, EnumString};

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(Debug, Copy, Clone, AsRefStr, EnumString, PartialEq, Default)]
#[strum(serialize_all = "snake_case")]
enum TypeCastingStyle {
    #[default]
    Consistent,
    Cast,
    Convert,
    Shorthand,
    None,
}

#[derive(Copy, Clone)]
struct PreviousSkipped;

fn get_children(segments: Segments) -> Segments {
    segments.children(Some(|it: &ErasedSegment| {
        !it.is_meta()
            && !matches!(
                it.get_type(),
                SyntaxKind::StartBracket
                    | SyntaxKind::EndBracket
                    | SyntaxKind::Whitespace
                    | SyntaxKind::Newline
                    | SyntaxKind::CastingOperator
                    | SyntaxKind::Comma
                    | SyntaxKind::Keyword
            )
    }))
}

fn shorthand_fix_list(
    tables: &Tables,
    root_segment: ErasedSegment,
    shorthand_arg_1: ErasedSegment,
    shorthand_arg_2: ErasedSegment,
) -> Vec<LintFix> {
    let mut edits = if shorthand_arg_1.get_raw_segments().len() > 1 {
        vec![
            SegmentBuilder::token(tables.next_id(), "(", SyntaxKind::StartBracket).finish(),
            shorthand_arg_1,
            SegmentBuilder::token(tables.next_id(), ")", SyntaxKind::EndBracket).finish(),
        ]
    } else {
        vec![shorthand_arg_1]
    };

    edits.extend([
        SegmentBuilder::token(tables.next_id(), "::", SyntaxKind::CastingOperator).finish(),
        shorthand_arg_2,
    ]);

    vec![LintFix::replace(root_segment, edits, None)]
}

#[derive(Clone, Debug, Default)]
pub struct RuleCV11 {
    preferred_type_casting_style: TypeCastingStyle,
}

impl Rule for RuleCV11 {
    fn load_from_config(&self, config: &AHashMap<String, Value>) -> Result<ErasedRule, String> {
        Ok(RuleCV11 {
            preferred_type_casting_style: config["preferred_type_casting_style"]
                .as_string()
                .unwrap()
                .parse()
                .unwrap(),
        }
        .erased())
    }

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

    fn description(&self) -> &'static str {
        "Enforce consistent type casting style."
    }

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

Using a mixture of `CONVERT`, `::`, and `CAST` when `preferred_type_casting_style` config is set to `consistent` (default).

```sql
SELECT
    CONVERT(int, 1) AS bar,
    100::int::text,
    CAST(10 AS text) AS coo
FROM foo;
```

**Best Practice**

Use a consistent type casting style.

```sql
SELECT
    CAST(1 AS int) AS bar,
    CAST(CAST(100 AS int) AS text),
    CAST(10 AS text) AS coo
FROM foo;
```
"
    }

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

    fn eval(&self, context: RuleContext) -> Vec<LintResult> {
        let current_type_casting_style = if context.segment.is_type(SyntaxKind::Function) {
            let Some(function_name) = context
                .segment
                .child(const { &SyntaxSet::new(&[SyntaxKind::FunctionName]) })
            else {
                return Vec::new();
            };
            if function_name.raw().eq_ignore_ascii_case("CAST") {
                TypeCastingStyle::Cast
            } else if function_name.raw().eq_ignore_ascii_case("CONVERT") {
                TypeCastingStyle::Convert
            } else {
                TypeCastingStyle::None
            }
        } else if context.segment.is_type(SyntaxKind::CastExpression) {
            TypeCastingStyle::Shorthand
        } else {
            TypeCastingStyle::None
        };

        let functional_context = FunctionalContext::new(context.clone());
        match self.preferred_type_casting_style {
            TypeCastingStyle::Consistent => {
                let Some(prior_type_casting_style) = context.try_get::<TypeCastingStyle>() else {
                    context.set(current_type_casting_style);
                    return Vec::new();
                };
                let previous_skipped = context.try_get::<PreviousSkipped>();

                let mut fixes = Vec::new();
                match prior_type_casting_style {
                    TypeCastingStyle::Cast => match current_type_casting_style {
                        TypeCastingStyle::Convert => {
                            let convert_content =
                                get_children(functional_context.segment().children(Some(
                                    |it: &ErasedSegment| it.is_type(SyntaxKind::Bracketed),
                                )));
                            if convert_content.len() > 2 {
                                if previous_skipped.is_none() {
                                    context.set(PreviousSkipped);
                                }
                                return Vec::new();
                            }

                            fixes = cast_fix_list(
                                context.tables,
                                context.segment.clone(),
                                &[convert_content[1].clone()],
                                convert_content[0].clone(),
                                None,
                            );
                        }
                        TypeCastingStyle::Shorthand => {
                            let expression_datatype_segment =
                                get_children(functional_context.segment());

                            fixes = cast_fix_list(
                                context.tables,
                                context.segment.clone(),
                                &[expression_datatype_segment[0].clone()],
                                expression_datatype_segment[1].clone(),
                                Some(Segments::from_vec(
                                    expression_datatype_segment.base[2..].to_vec(),
                                    None,
                                )),
                            )
                        }
                        _ => {}
                    },
                    TypeCastingStyle::Convert => match current_type_casting_style {
                        TypeCastingStyle::Cast => {
                            let cast_content = get_children(functional_context.segment().children(
                                Some(|it: &ErasedSegment| it.is_type(SyntaxKind::Bracketed)),
                            ));

                            if cast_content.len() > 2 {
                                return Vec::new();
                            }

                            fixes = convert_fix_list(
                                context.tables,
                                context.segment.clone(),
                                cast_content[1].clone(),
                                cast_content[0].clone(),
                                None,
                            );
                        }
                        TypeCastingStyle::Shorthand => {
                            let expression_datatype_segment =
                                get_children(functional_context.segment());

                            fixes = convert_fix_list(
                                context.tables,
                                context.segment.clone(),
                                expression_datatype_segment[1].clone(),
                                expression_datatype_segment[0].clone(),
                                Some(Segments::from_vec(
                                    expression_datatype_segment.base[2..].to_vec(),
                                    None,
                                )),
                            );
                        }
                        _ => (),
                    },
                    TypeCastingStyle::Shorthand => {
                        if current_type_casting_style == TypeCastingStyle::Cast {
                            // Get the content of CAST
                            let cast_content = get_children(functional_context.segment().children(
                                Some(|it: &ErasedSegment| it.is_type(SyntaxKind::Bracketed)),
                            ));
                            if cast_content.len() > 2 {
                                return Vec::new();
                            }

                            fixes = shorthand_fix_list(
                                context.tables,
                                context.segment.clone(),
                                cast_content[0].clone(),
                                cast_content[1].clone(),
                            );
                        } else if current_type_casting_style == TypeCastingStyle::Convert {
                            let convert_content =
                                get_children(functional_context.segment().children(Some(
                                    |it: &ErasedSegment| it.is_type(SyntaxKind::Bracketed),
                                )));
                            if convert_content.len() > 2 {
                                return Vec::new();
                            }

                            fixes = shorthand_fix_list(
                                context.tables,
                                context.segment.clone(),
                                convert_content[1].clone(),
                                convert_content[0].clone(),
                            );
                        }
                    }
                    _ => {}
                }

                if prior_type_casting_style != current_type_casting_style {
                    return vec![LintResult::new(
                        context.segment.clone().into(),
                        fixes,
                        None,
                        "Inconsistent type casting styles found.".to_owned().into(),
                        None,
                    )];
                }
            }
            _ if current_type_casting_style != self.preferred_type_casting_style => {
                let mut convert_content = None;
                let mut cast_content = None;
                let mut fixes = Vec::new();

                match self.preferred_type_casting_style {
                    TypeCastingStyle::Cast => match current_type_casting_style {
                        TypeCastingStyle::Convert => {
                            let segments = get_children(functional_context.segment().children(
                                Some(|it: &ErasedSegment| it.is_type(SyntaxKind::Bracketed)),
                            ));
                            fixes = cast_fix_list(
                                context.tables,
                                context.segment.clone(),
                                &[segments[1].clone()],
                                segments[0].clone(),
                                None,
                            );
                            convert_content = Some(segments);
                        }
                        TypeCastingStyle::Shorthand => {
                            let expression_datatype_segment =
                                get_children(functional_context.segment());
                            let data_type_idx = expression_datatype_segment
                                .iter()
                                .position(|seg| seg.is_type(SyntaxKind::DataType))
                                .unwrap();

                            fixes = cast_fix_list(
                                context.tables,
                                context.segment.clone(),
                                &expression_datatype_segment[..data_type_idx],
                                expression_datatype_segment[data_type_idx].clone(),
                                Some(Segments::from_vec(
                                    expression_datatype_segment.base[data_type_idx + 1..].to_vec(),
                                    None,
                                )),
                            );
                        }
                        _ => {}
                    },
                    TypeCastingStyle::Convert => match current_type_casting_style {
                        TypeCastingStyle::Cast => {
                            let cast_content = get_children(functional_context.segment().children(
                                Some(|it: &ErasedSegment| it.is_type(SyntaxKind::Bracketed)),
                            ));

                            fixes = convert_fix_list(
                                context.tables,
                                context.segment.clone(),
                                cast_content[1].clone(),
                                cast_content[0].clone(),
                                None,
                            );
                        }
                        TypeCastingStyle::Shorthand => {
                            let cast_content = get_children(functional_context.segment());

                            fixes = convert_fix_list(
                                context.tables,
                                context.segment.clone(),
                                cast_content[1].clone(),
                                cast_content[0].clone(),
                                Some(Segments::from_vec(cast_content.base[2..].to_vec(), None)),
                            )
                        }
                        _ => {}
                    },
                    TypeCastingStyle::Shorthand => match current_type_casting_style {
                        TypeCastingStyle::Cast => {
                            let segments = get_children(functional_context.segment().children(
                                Some(|it: &ErasedSegment| it.is_type(SyntaxKind::Bracketed)),
                            ));

                            fixes = shorthand_fix_list(
                                context.tables,
                                context.segment.clone(),
                                segments[0].clone(),
                                segments[1].clone(),
                            );
                            cast_content = Some(segments);
                        }
                        TypeCastingStyle::Convert => {
                            let segments = get_children(functional_context.segment().children(
                                Some(|it: &ErasedSegment| it.is_type(SyntaxKind::Bracketed)),
                            ));

                            fixes = shorthand_fix_list(
                                context.tables,
                                context.segment.clone(),
                                segments[1].clone(),
                                segments[0].clone(),
                            );

                            convert_content = Some(segments);
                        }
                        _ => {}
                    },
                    _ => {}
                }

                if convert_content
                    .filter(|convert_content| convert_content.len() > 2)
                    .is_some()
                {
                    fixes.clear();
                }

                if cast_content
                    .filter(|cast_content| cast_content.len() > 2)
                    .is_some()
                {
                    fixes.clear();
                }

                return vec![LintResult::new(
                    context.segment.clone().into(),
                    fixes,
                    None,
                    "Used type casting style is different from the preferred type casting style."
                        .to_owned()
                        .into(),
                    None,
                )];
            }

            _ => {}
        }

        Vec::new()
    }

    fn is_fix_compatible(&self) -> bool {
        true
    }

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

fn convert_fix_list(
    tables: &Tables,
    root: ErasedSegment,
    convert_arg_1: ErasedSegment,
    convert_arg_2: ErasedSegment,
    later_types: Option<Segments>,
) -> Vec<LintFix> {
    use sqruff_lib_core::parser::segments::base::ErasedSegment;

    let mut edits: Vec<ErasedSegment> = vec![
        SegmentBuilder::token(
            tables.next_id(),
            "convert",
            SyntaxKind::FunctionNameIdentifier,
        )
        .finish(),
        SegmentBuilder::token(tables.next_id(), "(", SyntaxKind::StartBracket).finish(),
        convert_arg_1,
        SegmentBuilder::token(tables.next_id(), ",", SyntaxKind::Comma).finish(),
        SegmentBuilder::whitespace(tables.next_id(), " "),
        convert_arg_2,
        SegmentBuilder::token(tables.next_id(), ")", SyntaxKind::EndBracket).finish(),
    ];

    if let Some(later_types) = later_types {
        let pre_edits: Vec<ErasedSegment> = vec![
            SegmentBuilder::token(
                tables.next_id(),
                "convert",
                SyntaxKind::FunctionNameIdentifier,
            )
            .finish(),
            SegmentBuilder::symbol(tables.next_id(), "("),
        ];

        let in_edits: Vec<ErasedSegment> = vec![
            SegmentBuilder::symbol(tables.next_id(), ","),
            SegmentBuilder::whitespace(tables.next_id(), " "),
        ];

        let post_edits: Vec<ErasedSegment> = vec![SegmentBuilder::symbol(tables.next_id(), ")")];

        for _type in later_types.base {
            edits = chain(
                chain(pre_edits.clone(), vec![_type]),
                chain(in_edits.clone(), chain(edits, post_edits.clone())),
            )
            .collect();
        }
    }

    vec![LintFix::replace(root, edits, None)]
}

fn cast_fix_list(
    tables: &Tables,
    root: ErasedSegment,
    cast_arg_1: &[ErasedSegment],
    cast_arg_2: ErasedSegment,
    later_types: Option<Segments>,
) -> Vec<LintFix> {
    let mut edits = vec![
        SegmentBuilder::token(tables.next_id(), "cast", SyntaxKind::FunctionNameIdentifier)
            .finish(),
        SegmentBuilder::token(tables.next_id(), "(", SyntaxKind::StartBracket).finish(),
    ];
    edits.extend_from_slice(cast_arg_1);
    edits.extend([
        SegmentBuilder::whitespace(tables.next_id(), " "),
        SegmentBuilder::keyword(tables.next_id(), "as"),
        SegmentBuilder::whitespace(tables.next_id(), " "),
        cast_arg_2,
        SegmentBuilder::token(tables.next_id(), ")", SyntaxKind::EndBracket).finish(),
    ]);

    if let Some(later_types) = later_types {
        let pre_edits: Vec<ErasedSegment> = vec![
            SegmentBuilder::token(tables.next_id(), "cast", SyntaxKind::FunctionNameIdentifier)
                .finish(),
            SegmentBuilder::symbol(tables.next_id(), "("),
        ];

        let in_edits: Vec<ErasedSegment> = vec![
            SegmentBuilder::whitespace(tables.next_id(), " "),
            SegmentBuilder::keyword(tables.next_id(), "as"),
            SegmentBuilder::whitespace(tables.next_id(), " "),
        ];

        let post_edits: Vec<ErasedSegment> = vec![SegmentBuilder::symbol(tables.next_id(), ")")];

        for _type in later_types.base {
            let mut xs = Vec::new();
            xs.extend(pre_edits.clone());
            xs.extend(edits);
            xs.extend(in_edits.clone());
            xs.push(_type);
            xs.extend(post_edits.clone());
            edits = xs;
        }
    }

    vec![LintFix::replace(root, edits, None)]
}