sqruff_lib/rules/references/
rf03.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
use std::cell::RefCell;

use ahash::{AHashMap, AHashSet};
use itertools::Itertools;
use smol_str::SmolStr;
use sqruff_lib_core::dialects::common::{AliasInfo, ColumnAliasInfo};
use sqruff_lib_core::dialects::init::DialectKind;
use sqruff_lib_core::dialects::syntax::{SyntaxKind, SyntaxSet};
use sqruff_lib_core::helpers::capitalize;
use sqruff_lib_core::lint_fix::LintFix;
use sqruff_lib_core::parser::segments::base::{ErasedSegment, SegmentBuilder, Tables};
use sqruff_lib_core::parser::segments::object_reference::ObjectReferenceSegment;
use sqruff_lib_core::utils::analysis::query::Query;

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};

#[derive(Debug, Clone, Default)]
pub struct RuleRF03 {
    single_table_references: Option<String>,
    force_enable: bool,
}

impl RuleRF03 {
    fn visit_queries(
        tables: &Tables,
        single_table_references: &str,
        is_struct_dialect: bool,
        query: Query<()>,
        _visited: &mut AHashSet<ErasedSegment>,
    ) -> Vec<LintResult> {
        #[allow(unused_assignments)]
        let mut select_info = None;

        let mut acc = Vec::new();
        let selectables = &RefCell::borrow(&query.inner).selectables;

        if !selectables.is_empty() {
            select_info = selectables[0].select_info();

            if let Some(select_info) = select_info
                .clone()
                .filter(|select_info| select_info.table_aliases.len() == 1)
            {
                let mut fixable = true;
                let possible_ref_tables = iter_available_targets(query.clone());

                if let Some(_parent) = &RefCell::borrow(&query.inner).parent {}

                if possible_ref_tables.len() > 1 {
                    fixable = false;
                }

                let results = check_references(
                    tables,
                    select_info.table_aliases,
                    select_info.standalone_aliases,
                    select_info.reference_buffer,
                    select_info.col_aliases,
                    single_table_references,
                    is_struct_dialect,
                    Some("qualified".into()),
                    fixable,
                );

                acc.extend(results);
            }
        }

        let children = query.children();
        for child in children {
            acc.extend(Self::visit_queries(
                tables,
                single_table_references,
                is_struct_dialect,
                child,
                _visited,
            ));
        }

        acc
    }
}

fn iter_available_targets(query: Query<()>) -> Vec<SmolStr> {
    RefCell::borrow(&query.inner)
        .selectables
        .iter()
        .flat_map(|selectable| {
            selectable
                .select_info()
                .unwrap()
                .table_aliases
                .iter()
                .map(|alias| alias.ref_str.clone())
                .collect_vec()
        })
        .collect_vec()
}

#[allow(clippy::too_many_arguments)]
fn check_references(
    tables: &Tables,
    table_aliases: Vec<AliasInfo>,
    standalone_aliases: Vec<SmolStr>,
    references: Vec<ObjectReferenceSegment>,
    col_aliases: Vec<ColumnAliasInfo>,
    single_table_references: &str,
    is_struct_dialect: bool,
    fix_inconsistent_to: Option<String>,
    fixable: bool,
) -> Vec<LintResult> {
    let mut acc = Vec::new();

    let col_alias_names = col_aliases
        .clone()
        .into_iter()
        .map(|it| it.alias_identifier_name)
        .collect_vec();

    let table_ref_str = &table_aliases[0].ref_str;
    let table_ref_str_source = table_aliases[0].segment.clone();
    let mut seen_ref_types = AHashSet::new();

    for reference in references.clone() {
        let mut this_ref_type = reference.qualification();
        if this_ref_type == "qualified"
            && is_struct_dialect
            && &reference
                .iter_raw_references()
                .into_iter()
                .next()
                .unwrap()
                .part
                != table_ref_str
        {
            this_ref_type = "unqualified";
        }

        let lint_res = validate_one_reference(
            tables,
            single_table_references,
            reference,
            this_ref_type,
            &standalone_aliases,
            table_ref_str,
            table_ref_str_source.clone(),
            &col_alias_names,
            &seen_ref_types,
            fixable,
        );

        seen_ref_types.insert(this_ref_type);
        let Some(lint_res) = lint_res else {
            continue;
        };

        if let Some(fix_inconsistent_to) = fix_inconsistent_to
            .as_ref()
            .filter(|_| single_table_references == "consistent")
        {
            let results = check_references(
                tables,
                table_aliases.clone(),
                standalone_aliases.clone(),
                references.clone(),
                col_aliases.clone(),
                fix_inconsistent_to,
                is_struct_dialect,
                None,
                fixable,
            );

            acc.extend(results);
        }

        acc.push(lint_res);
    }

    acc
}

#[allow(clippy::too_many_arguments)]
fn validate_one_reference(
    tables: &Tables,
    single_table_references: &str,
    ref_: ObjectReferenceSegment,
    this_ref_type: &str,
    standalone_aliases: &[SmolStr],
    table_ref_str: &str,
    _table_ref_str_source: Option<ErasedSegment>,
    col_alias_names: &[SmolStr],
    seen_ref_types: &AHashSet<&str>,
    fixable: bool,
) -> Option<LintResult> {
    if !ref_.is_qualified() && ref_.0.is_type(SyntaxKind::WildcardIdentifier) {
        return None;
    }

    if standalone_aliases.contains(ref_.0.raw()) {
        return None;
    }

    if table_ref_str.is_empty() {
        return None;
    }

    if col_alias_names.contains(ref_.0.raw()) {
        return None;
    }

    if single_table_references == "consistent" {
        return if !seen_ref_types.is_empty() && !seen_ref_types.contains(this_ref_type) {
            LintResult::new(
                ref_.clone().0.into(),
                Vec::new(),
                None,
                format!(
                    "{} reference '{}' found in single table select which is inconsistent with \
                     previous references.",
                    capitalize(this_ref_type),
                    ref_.0.raw()
                )
                .into(),
                None,
            )
            .into()
        } else {
            None
        };
    }

    if single_table_references == this_ref_type {
        return None;
    }

    if single_table_references == "unqualified" {
        let fixes = if fixable {
            ref_.0
                .segments()
                .iter()
                .take(2)
                .cloned()
                .map(LintFix::delete)
                .collect::<Vec<_>>()
        } else {
            Vec::new()
        };

        return LintResult::new(
            ref_.0.clone().into(),
            fixes,
            None,
            format!(
                "{} reference '{}' found in single table select.",
                capitalize(this_ref_type),
                ref_.0.raw()
            )
            .into(),
            None,
        )
        .into();
    }

    let ref_ = ref_.0.clone();
    let fixes = if fixable {
        vec![LintFix::create_before(
            if !ref_.segments().is_empty() {
                ref_.segments()[0].clone()
            } else {
                ref_.clone()
            },
            vec![
                SegmentBuilder::token(tables.next_id(), table_ref_str, SyntaxKind::NakedIdentifier)
                    .finish(),
                SegmentBuilder::symbol(tables.next_id(), "."),
            ],
        )]
    } else {
        Vec::new()
    };

    LintResult::new(
        ref_.clone().into(),
        fixes,
        None,
        format!(
            "{} reference '{}' found in single table select.",
            capitalize(this_ref_type),
            ref_.raw()
        )
        .into(),
        None,
    )
    .into()
}

impl Rule for RuleRF03 {
    fn load_from_config(&self, config: &AHashMap<String, Value>) -> Result<ErasedRule, String> {
        Ok(RuleRF03 {
            single_table_references: config
                .get("single_table_references")
                .and_then(|it| it.as_string().map(ToString::to_string)),
            force_enable: config["force_enable"].as_bool().unwrap(),
        }
        .erased())
    }

    fn name(&self) -> &'static str {
        "references.consistent"
    }

    fn description(&self) -> &'static str {
        "References should be consistent in statements with a single table."
    }

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

In this example, only the field b is referenced.

```sql
SELECT
    a,
    foo.b
FROM foo
```

**Best practice**

Add or remove references to all fields.

```sql
SELECT
    a,
    b
FROM foo

-- Also good

SELECT
    foo.a,
    foo.b
FROM foo
```
"#
    }

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

    fn force_enable(&self) -> bool {
        self.force_enable
    }

    fn dialect_skip(&self) -> &'static [DialectKind] {
        // TODO: add hive
        &[DialectKind::Bigquery, DialectKind::Redshift]
    }

    fn eval(&self, context: RuleContext) -> Vec<LintResult> {
        let single_table_references =
            self.single_table_references.as_deref().unwrap_or_else(|| {
                context.config.raw["rules"]["single_table_references"]
                    .as_string()
                    .unwrap()
            });

        let query: Query<()> = Query::from_segment(&context.segment, context.dialect, None);
        let mut visited: AHashSet<ErasedSegment> = AHashSet::new();
        let is_struct_dialect = self.dialect_skip().contains(&context.dialect.name);

        Self::visit_queries(
            context.tables,
            single_table_references,
            is_struct_dialect,
            query,
            &mut visited,
        )
    }

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

    fn crawl_behaviour(&self) -> Crawler {
        SegmentSeekerCrawler::new(
            const {
                SyntaxSet::new(&[
                    SyntaxKind::SelectStatement,
                    SyntaxKind::SetExpression,
                    SyntaxKind::WithCompoundStatement,
                ])
            },
        )
        .disallow_recurse()
        .into()
    }
}