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

use crate::core::config::Value;
use crate::core::parser::segments::base::{
    ErasedSegment, NewlineSegment, WhitespaceSegment, WhitespaceSegmentNewArgs,
};
use crate::core::rules::base::{Erased, ErasedRule, LintFix, LintResult, Rule};
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>) -> ErasedRule {
        RuleLT10::default().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 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("select_clause_modifier")));

        // 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| seg.is_type("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| seg.is_type("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| seg.is_type("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![
            WhitespaceSegment::create(" ", &<_>::default(), WhitespaceSegmentNewArgs),
            select_clause_modifier.clone_box(),
        ];

        if trailing_newline_segments.is_empty() {
            edit_segments.push(NewlineSegment::create("\n", &<_>::default(), <_>::default()));
        }

        let mut fixes = Vec::new();
        // Move select clause modifier after select keyword.
        fixes.push(LintFix::create_after(select_keyword.clone_box(), 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| segment.is_whitespace()),
            Some(|seg| seg.is_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_box()));

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

    fn crawl_behaviour(&self) -> Crawler {
        SegmentSeekerCrawler::new(["select_clause"].into()).into()
    }
}

#[cfg(test)]
mod tests {
    use pretty_assertions::assert_eq;

    use crate::api::simple::fix;
    use crate::core::rules::base::{Erased, ErasedRule};
    use crate::rules::layout::LT10::RuleLT10;

    fn rules() -> Vec<ErasedRule> {
        vec![RuleLT10::default().erased()]
    }

    #[test]
    fn test_fail_distinct_on_next_line_1() {
        let fail_str = "
SELECT
    DISTINCT user_id,
    list_id
FROM
    safe_user";

        let fix_str = fix(fail_str.into(), rules());
        assert_eq!(
            fix_str,
            "
SELECT DISTINCT
    user_id,
    list_id
FROM
    safe_user"
        );
    }

    #[test]
    fn test_fail_distinct_on_next_line_2() {
        let fail_str = "
SELECT
    -- The table contains duplicates, so we use DISTINCT.
    DISTINCT user_id
FROM
    safe_user";

        let fix_str = fix(fail_str.into(), rules());
        assert_eq!(
            fix_str,
            "
SELECT DISTINCT
    -- The table contains duplicates, so we use DISTINCT.
    user_id
FROM
    safe_user"
        );
    }

    #[test]
    fn test_fail_distinct_on_next_line_3() {
        let fail_str = "
select
distinct
    abc,
    def
from a;";

        let fix_str = fix(fail_str.into(), rules());
        println!("{}", &fix_str);
    }
}