sqruff_lib/rules/ambiguous/
am03.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
use ahash::{AHashMap, AHashSet};
use smol_str::{SmolStr, StrExt};
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::{CloneRule, ErasedRule, LintResult, Rule, RuleGroups};
use crate::core::rules::context::RuleContext;
use crate::core::rules::crawlers::{Crawler, SegmentSeekerCrawler};

#[derive(Clone, Debug, Default)]
pub struct RuleAM03;

impl Rule for RuleAM03 {
    fn load_from_config(&self, _config: &AHashMap<String, Value>) -> Result<ErasedRule, String> {
        Ok(RuleAM03.erased())
    }

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

    fn description(&self) -> &'static str {
        "Ambiguous ordering directions for columns in order by clause."
    }

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

In this example, the `ORDER BY` clause is ambiguous because some columns are explicitly ordered, while others are not.

```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::Ambiguous]
    }

    fn eval(&self, context: RuleContext) -> Vec<LintResult> {
        // Only trigger on orderby_clause
        let order_by_spec = Self::get_order_by_info(context.segment.clone());
        let order_types = order_by_spec
            .iter()
            .map(|spec| spec.order.clone())
            .collect::<AHashSet<Option<_>>>();

        // If all or no columns are explicitly ordered, then it's not ambiguous
        if !order_types.contains(&None) || (order_types.len() == 1 && order_types.contains(&None)) {
            return vec![];
        }

        // If there is a mix of explicit and implicit ordering, then it's ambiguous
        let fixes = order_by_spec
            .into_iter()
            .filter(|spec| spec.order.is_none())
            .map(|spec| {
                LintFix::create_after(
                    spec.column_reference,
                    vec![
                        SegmentBuilder::whitespace(context.tables.next_id(), " "),
                        SegmentBuilder::keyword(context.tables.next_id(), "ASC"),
                    ],
                    None,
                )
            })
            .collect();

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

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

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

/// For AM03, segment that ends an ORDER BY column and any order provided.
struct OrderByColumnInfo {
    column_reference: ErasedSegment,
    order: Option<SmolStr>,
}

impl RuleAM03 {
    fn get_order_by_info(segment: ErasedSegment) -> Vec<OrderByColumnInfo> {
        assert!(segment.is_type(SyntaxKind::OrderbyClause));

        let mut result = vec![];
        let mut column_reference = None;
        let mut ordering_reference = None;

        for child_segment in segment.segments() {
            if child_segment.is_type(SyntaxKind::ColumnReference) {
                column_reference = Some(child_segment.clone());
            } else if child_segment.is_type(SyntaxKind::Keyword)
                && (child_segment.raw().eq_ignore_ascii_case("ASC")
                    || child_segment.raw().eq_ignore_ascii_case("DESC"))
            {
                ordering_reference = Some(child_segment.raw().to_uppercase_smolstr());
            };

            if column_reference.is_some() && child_segment.raw() == "," {
                result.push(OrderByColumnInfo {
                    column_reference: column_reference.clone().unwrap(),
                    order: ordering_reference.clone(),
                });

                column_reference = None;
                ordering_reference = None;
            }
        }
        // Special handling for last column
        if column_reference.is_some() {
            result.push(OrderByColumnInfo {
                column_reference: column_reference.clone().unwrap(),
                order: ordering_reference.clone(),
            });
        }

        result
    }
}