sqruff_lib/rules/layout/
lt10.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
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};

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

impl Rule for RuleLT10 {
    fn load_from_config(&self, _config: &AHashMap<String, Value>) -> Result<ErasedRule, String> {
        Ok(RuleLT10.erased())
    }
    fn name(&self) -> &'static str {
        "layout.select_modifiers"
    }

    fn description(&self) -> &'static str {
        "'SELECT' modifiers (e.g. 'DISTINCT') must be on the same line as 'SELECT'."
    }

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

In this example, the `DISTINCT` modifier is on the next line after the `SELECT` keyword.

```sql
select
    distinct a,
    b
from x
```

**Best practice**

Move the `DISTINCT` modifier to the same line as the `SELECT` keyword.

```sql
select distinct
    a,
    b
from x
```
"#
    }

    fn groups(&self) -> &'static [RuleGroups] {
        &[RuleGroups::All, RuleGroups::Core, RuleGroups::Layout]
    }
    fn eval(&self, context: RuleContext) -> Vec<LintResult> {
        // Get children of select_clause and the corresponding select keyword.
        let child_segments = FunctionalContext::new(context.clone())
            .segment()
            .children(None);
        let select_keyword = child_segments.first().unwrap();

        // See if we have a select_clause_modifier.
        let select_clause_modifier_seg = child_segments.find_first(Some(|sp: &ErasedSegment| {
            sp.is_type(SyntaxKind::SelectClauseModifier)
        }));

        // Rule doesn't apply if there's no select clause modifier.
        if select_clause_modifier_seg.is_empty() {
            return Vec::new();
        }

        // Are there any newlines between the select keyword and the select clause
        // modifier.
        let leading_newline_segments = child_segments.select(
            Some(|seg: &ErasedSegment| seg.is_type(SyntaxKind::Newline)),
            Some(|seg| seg.is_whitespace() || seg.is_meta()),
            select_keyword.into(),
            None,
        );

        // Rule doesn't apply if select clause modifier is already on the same line as
        // the select keyword.
        if leading_newline_segments.is_empty() {
            return Vec::new();
        }

        let select_clause_modifier = select_clause_modifier_seg.first().unwrap();

        // We should check if there is whitespace before the select clause modifier and
        // remove this during the lint fix.
        let leading_whitespace_segments = child_segments.select(
            Some(|seg: &ErasedSegment| seg.is_type(SyntaxKind::Whitespace)),
            Some(|seg| seg.is_whitespace() || seg.is_meta()),
            select_keyword.into(),
            None,
        );

        // We should also check if the following select clause element
        // is on the same line as the select clause modifier.
        let trailing_newline_segments = child_segments.select(
            Some(|seg: &ErasedSegment| seg.is_type(SyntaxKind::Newline)),
            Some(|seg| seg.is_whitespace() || seg.is_meta()),
            select_clause_modifier.into(),
            None,
        );

        // We will insert these segments directly after the select keyword.
        let mut edit_segments = vec![
            SegmentBuilder::whitespace(context.tables.next_id(), " "),
            select_clause_modifier.clone(),
        ];

        if trailing_newline_segments.is_empty() {
            edit_segments.push(SegmentBuilder::newline(context.tables.next_id(), "\n"));
        }

        let mut fixes = Vec::new();
        // Move select clause modifier after select keyword.
        fixes.push(LintFix::create_after(
            select_keyword.clone(),
            edit_segments,
            None,
        ));

        if trailing_newline_segments.is_empty() {
            fixes.extend(leading_newline_segments.into_iter().map(LintFix::delete));
        } else {
            let segments = chain(leading_newline_segments, leading_whitespace_segments);
            fixes.extend(segments.map(LintFix::delete));
        }

        let trailing_whitespace_segments = child_segments.select(
            Some(|segment: &ErasedSegment| segment.is_whitespace()),
            Some(|seg| seg.is_type(SyntaxKind::Whitespace) || seg.is_meta()),
            select_clause_modifier.into(),
            None,
        );

        if !trailing_whitespace_segments.is_empty() {
            fixes.extend(
                trailing_whitespace_segments
                    .into_iter()
                    .map(LintFix::delete),
            );
        }

        // Delete the original select clause modifier.
        fixes.push(LintFix::delete(select_clause_modifier.clone()));

        vec![LintResult::new(
            context.segment.into(),
            fixes,
            None,
            None,
            None,
        )]
    }

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

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