sqruff_lib/rules/ambiguous/
am06.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
use ahash::AHashMap;
use sqruff_lib_core::dialects::syntax::{SyntaxKind, SyntaxSet};

use crate::core::config::Value;
use crate::core::rules::base::{CloneRule, ErasedRule, LintResult, Rule, RuleGroups};
use crate::core::rules::context::RuleContext;
use crate::core::rules::crawlers::{Crawler, SegmentSeekerCrawler};
use crate::utils::functional::context::FunctionalContext;

#[derive(Clone, Copy)]
struct PriorGroupByOrderByConvention(GroupByAndOrderByConvention);

#[derive(Debug, Clone)]
pub struct RuleAM06 {
    group_by_and_order_by_style: GroupByAndOrderByConvention,
}

impl Default for RuleAM06 {
    fn default() -> Self {
        Self {
            group_by_and_order_by_style: GroupByAndOrderByConvention::Consistent,
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, strum_macros::EnumString)]
#[strum(serialize_all = "lowercase")]
enum GroupByAndOrderByConvention {
    Consistent,
    Explicit,
    Implicit,
}

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

    fn name(&self) -> &'static str {
        "ambiguous.column_references"
    }

    fn description(&self) -> &'static str {
        "Inconsistent column references in 'GROUP BY/ORDER BY' clauses."
    }

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

In this example, the ORRDER BY clause mixes explicit and implicit order by column references.

```sql
SELECT
    a, b
FROM foo
ORDER BY a, b DESC
```

**Best practice**

If any columns in the ORDER BY clause specify ASC or DESC, they should all do so.

```sql
SELECT
    a, b
FROM foo
ORDER BY a ASC, b DESC
```
"#
    }
    fn groups(&self) -> &'static [RuleGroups] {
        &[RuleGroups::All, RuleGroups::Core, RuleGroups::Ambiguous]
    }

    fn eval(&self, context: RuleContext) -> Vec<LintResult> {
        let skip = FunctionalContext::new(context.clone())
            .parent_stack()
            .any(Some(|it| {
                let ignore_types = [
                    SyntaxKind::WithingroupClause,
                    SyntaxKind::WindowSpecification,
                    SyntaxKind::AggregateOrderByClause,
                ];
                ignore_types.iter().any(|&ty| it.is_type(ty))
            }));

        if skip {
            return Vec::new();
        }

        // Initialize the map
        let mut column_reference_category_map = AHashMap::new();
        column_reference_category_map.insert(
            SyntaxKind::ColumnReference,
            GroupByAndOrderByConvention::Explicit,
        );
        column_reference_category_map.insert(
            SyntaxKind::Expression,
            GroupByAndOrderByConvention::Explicit,
        );
        column_reference_category_map.insert(
            SyntaxKind::NumericLiteral,
            GroupByAndOrderByConvention::Implicit,
        );

        let mut column_reference_category_set: Vec<_> = context
            .segment
            .segments()
            .iter()
            .filter_map(|segment| column_reference_category_map.get(&segment.get_type()))
            .collect();
        column_reference_category_set.dedup();

        if column_reference_category_set.is_empty() {
            return Vec::new();
        }

        if self.group_by_and_order_by_style == GroupByAndOrderByConvention::Consistent {
            if column_reference_category_set.len() > 1 {
                return vec![LintResult::new(
                    context.segment.into(),
                    Vec::new(),
                    None,
                    None,
                    None,
                )];
            } else {
                let current_group_by_order_by_convention =
                    column_reference_category_set.pop().copied().unwrap();

                if let Some(PriorGroupByOrderByConvention(prior_group_by_order_by_convention)) =
                    context.try_get::<PriorGroupByOrderByConvention>()
                {
                    if prior_group_by_order_by_convention != current_group_by_order_by_convention {
                        return vec![LintResult::new(
                            context.segment.into(),
                            Vec::new(),
                            None,
                            None,
                            None,
                        )];
                    }
                }

                context.set(PriorGroupByOrderByConvention(
                    current_group_by_order_by_convention,
                ));
            }
        } else if column_reference_category_set
            .into_iter()
            .any(|category| *category != self.group_by_and_order_by_style)
        {
            return vec![LintResult::new(
                context.segment.into(),
                Vec::new(),
                None,
                None,
                None,
            )];
        }

        vec![]
    }

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