dbtui 0.2.3

Terminal database client with Vim-style navigation
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
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
//! DiagnosticProvider — multi-pass SQL validation and lint rules.
//!
//! Three synchronous passes (instant, no I/O):
//! - Pass 1: Syntax validation via sqlparser (per-dialect)
//! - Pass 2: Semantic validation via SemanticAnalyzer (unknown tables/schemas)
//! - Pass 3: Lint rules (SELECT *, missing WHERE, JOIN without ON)
//!
//! Pass 4 (server-side compilation) is async and handled by the UI layer
//! via the adapter's `compile_check` method with debounce.

use sqlparser::parser::Parser;

use crate::sql_engine::analyzer::SemanticAnalyzer;
use crate::sql_engine::context::ResolutionErrorKind;
use crate::sql_engine::dialect::SqlDialect;
use crate::sql_engine::metadata::MetadataIndex;
use crate::sql_engine::tokenizer;

// ---------------------------------------------------------------------------
// Diagnostic types
// ---------------------------------------------------------------------------

/// Severity level of a diagnostic.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
#[allow(dead_code)]
pub enum DiagnosticSeverity {
    Error,
    Warning,
    Info,
    Hint,
}

/// Source of the diagnostic (which pass produced it).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[allow(dead_code)]
pub enum DiagnosticSource {
    /// Pass 1: sqlparser syntax validation.
    Syntax,
    /// Pass 2: semantic reference validation.
    Semantic,
    /// Pass 3: lint rules.
    Lint,
    /// Pass 4: server-side compilation (async, handled externally).
    Server,
}

/// A single diagnostic with position, message, severity, and source.
#[derive(Debug, Clone)]
#[allow(dead_code)]
pub struct Diagnostic {
    pub row: usize,
    pub col_start: usize,
    pub col_end: usize,
    pub message: String,
    pub severity: DiagnosticSeverity,
    pub source: DiagnosticSource,
}

/// Aggregated diagnostics for a buffer.
///
/// Supports source-based updates: replacing diagnostics from one source
/// while preserving diagnostics from other sources. This allows async
/// server diagnostics to arrive without clobbering local results.
#[derive(Debug, Clone, Default)]
#[allow(dead_code)]
pub struct DiagnosticSet {
    items: Vec<Diagnostic>,
    generation: u64,
}

#[allow(dead_code)]
impl DiagnosticSet {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn items(&self) -> &[Diagnostic] {
        &self.items
    }

    pub fn generation(&self) -> u64 {
        self.generation
    }

    pub fn is_empty(&self) -> bool {
        self.items.is_empty()
    }

    /// Replace diagnostics from a given source, preserving others.
    pub fn update_source(&mut self, source: DiagnosticSource, diags: Vec<Diagnostic>) {
        self.items.retain(|d| d.source != source);
        self.items.extend(diags);
        self.items.sort_by_key(|d| (d.row, d.col_start));
        self.generation += 1;
    }

    /// Clear all diagnostics.
    pub fn clear(&mut self) {
        self.items.clear();
        self.generation += 1;
    }

    /// Count of error-level diagnostics.
    pub fn error_count(&self) -> usize {
        self.items
            .iter()
            .filter(|d| d.severity == DiagnosticSeverity::Error)
            .count()
    }

    /// Count of warning-level diagnostics.
    pub fn warning_count(&self) -> usize {
        self.items
            .iter()
            .filter(|d| d.severity == DiagnosticSeverity::Warning)
            .count()
    }
}

// ---------------------------------------------------------------------------
// Diagnostic provider
// ---------------------------------------------------------------------------

/// Multi-pass diagnostic engine. All passes are synchronous.
pub struct DiagnosticProvider<'a> {
    dialect: &'a dyn SqlDialect,
    metadata: &'a MetadataIndex,
}

impl<'a> DiagnosticProvider<'a> {
    pub fn new(dialect: &'a dyn SqlDialect, metadata: &'a MetadataIndex) -> Self {
        Self { dialect, metadata }
    }

    /// Run all local passes (syntax + semantic + lint). Returns diagnostics.
    /// Tokenizes once and shares context across passes.
    pub fn check_local(&self, lines: &[String]) -> Vec<Diagnostic> {
        let mut diagnostics = Vec::new();

        // Pass 1: Syntax
        self.check_syntax(lines, &mut diagnostics);

        // Shared tokenization for passes 2+3
        let line_strs: Vec<&str> = lines.iter().map(|s| s.as_str()).collect();
        let tokens = tokenizer::tokenize_sql(&line_strs);

        // Pass 2: Semantic (table/schema references) + "did you mean?" suggestions
        self.check_references(lines, &mut diagnostics);

        // Pass 3: Lint (uses shared tokens)
        self.check_lint_with_tokens(&tokens, &mut diagnostics);

        diagnostics
    }

    // -----------------------------------------------------------------------
    // Pass 1: Syntax validation
    // -----------------------------------------------------------------------

    fn check_syntax(&self, lines: &[String], out: &mut Vec<Diagnostic>) {
        let dialect = self.dialect.parser_dialect();

        // Split into query blocks separated by blank lines
        let mut block_start = 0;
        let mut i = 0;
        while i <= lines.len() {
            let is_blank = i == lines.len() || lines[i].trim().is_empty();
            if is_blank && i > block_start {
                let block: String = lines[block_start..i]
                    .iter()
                    .map(|l| l.as_str())
                    .collect::<Vec<_>>()
                    .join("\n");
                if !block.trim().is_empty()
                    && let Err(e) = Parser::parse_sql(dialect.as_ref(), &block)
                {
                    let msg = e.to_string();
                    let (err_line, err_col) = parse_syntax_error_position(&msg);
                    let file_row = block_start + err_line.saturating_sub(1);
                    let file_col = if err_col > 0 { err_col - 1 } else { 0 };
                    let clean_msg = msg.split(" at Line:").next().unwrap_or(&msg).to_string();
                    let col_end = if file_row < lines.len() {
                        let line_len = lines[file_row].len();
                        if file_col < line_len {
                            line_len
                        } else {
                            file_col + 1
                        }
                    } else {
                        file_col + 1
                    };
                    out.push(Diagnostic {
                        row: file_row,
                        col_start: file_col,
                        col_end,
                        message: clean_msg,
                        severity: DiagnosticSeverity::Error,
                        source: DiagnosticSource::Syntax,
                    });
                }
                block_start = i + 1;
            } else if is_blank {
                block_start = i + 1;
            }
            i += 1;
        }
    }

    // -----------------------------------------------------------------------
    // Pass 2: Semantic reference validation
    // -----------------------------------------------------------------------

    fn check_references(&self, lines: &[String], out: &mut Vec<Diagnostic>) {
        // Skip semantic checks when metadata is not yet loaded — avoids
        // false "unknown table/schema" errors during connection warmup.
        if self.metadata.all_schemas().is_empty() {
            return;
        }

        let analyzer = SemanticAnalyzer::new(self.dialect, self.metadata);
        let ctx = analyzer.analyze_for_diagnostics(lines);

        for err in &ctx.resolution_errors {
            let severity = match err.kind {
                ResolutionErrorKind::UnknownSchema | ResolutionErrorKind::UnknownTable => {
                    DiagnosticSeverity::Error
                }
                ResolutionErrorKind::UnknownColumn | ResolutionErrorKind::AmbiguousColumn => {
                    DiagnosticSeverity::Warning
                }
            };
            // "Did you mean?" — fuzzy-match unknown names against metadata
            let suggestion = self.suggest_similar(&err.message, &err.kind);
            let message = if let Some(ref s) = suggestion {
                format!("{} — did you mean '{s}'?", err.message)
            } else {
                err.message.clone()
            };
            out.push(Diagnostic {
                row: err.location.row,
                col_start: err.location.col_start,
                col_end: err.location.col_end,
                message,
                severity,
                source: DiagnosticSource::Semantic,
            });
        }
    }

    // -----------------------------------------------------------------------
    // Pass 3: Lint rules
    // -----------------------------------------------------------------------

    /// Lint using pre-tokenized tokens (avoids re-tokenization).
    fn check_lint_with_tokens(&self, tokens: &[tokenizer::Token<'_>], out: &mut Vec<Diagnostic>) {
        self.lint_select_star_tokens(tokens, out);
        self.lint_missing_where_tokens(tokens, out);
        self.lint_join_without_on_tokens(tokens, out);
    }

    fn lint_select_star_tokens(&self, tokens: &[tokenizer::Token<'_>], out: &mut Vec<Diagnostic>) {
        let mut i = 0;
        while i < tokens.len() {
            if tokens[i].kind == tokenizer::TokenKind::Word
                && tokens[i].text.to_uppercase() == "SELECT"
            {
                // Skip whitespace after SELECT
                let mut j = i + 1;
                while j < tokens.len() && tokens[j].kind == tokenizer::TokenKind::Whitespace {
                    j += 1;
                }
                // Skip optional DISTINCT
                if j < tokens.len()
                    && tokens[j].kind == tokenizer::TokenKind::Word
                    && tokens[j].text.to_uppercase() == "DISTINCT"
                {
                    j += 1;
                    while j < tokens.len() && tokens[j].kind == tokenizer::TokenKind::Whitespace {
                        j += 1;
                    }
                }
                // Check for *
                if j < tokens.len()
                    && tokens[j].kind == tokenizer::TokenKind::Other
                    && tokens[j].text == "*"
                {
                    out.push(Diagnostic {
                        row: tokens[j].row,
                        col_start: tokens[j].col,
                        col_end: tokens[j].col + 1,
                        message: "SELECT * — consider listing columns explicitly".to_string(),
                        severity: DiagnosticSeverity::Warning,
                        source: DiagnosticSource::Lint,
                    });
                }
            }
            i += 1;
        }
    }

    fn lint_missing_where_tokens(
        &self,
        tokens: &[tokenizer::Token<'_>],
        out: &mut Vec<Diagnostic>,
    ) {
        let words: Vec<String> = tokens
            .iter()
            .filter(|t| t.kind == tokenizer::TokenKind::Word)
            .map(|t| t.text.to_uppercase())
            .collect();

        let has_where = words.iter().any(|w| w == "WHERE");

        for token in tokens {
            if token.kind != tokenizer::TokenKind::Word {
                continue;
            }
            let upper = token.text.to_uppercase();
            if (upper == "UPDATE" || upper == "DELETE") && !has_where {
                out.push(Diagnostic {
                    row: token.row,
                    col_start: token.col,
                    col_end: token.col + token.text.len(),
                    message: format!("{upper} without WHERE clause"),
                    severity: DiagnosticSeverity::Warning,
                    source: DiagnosticSource::Lint,
                });
                break; // One warning per block
            }
        }
    }

    fn lint_join_without_on_tokens(
        &self,
        tokens: &[tokenizer::Token<'_>],
        out: &mut Vec<Diagnostic>,
    ) {
        let mut i = 0;
        while i < tokens.len() {
            if tokens[i].kind == tokenizer::TokenKind::Word
                && tokens[i].text.to_uppercase() == "JOIN"
            {
                let join_token = &tokens[i];
                // Scan forward for ON or another JOIN/WHERE (which would mean ON is missing)
                let mut j = i + 1;
                let mut found_on = false;
                while j < tokens.len() {
                    if tokens[j].kind == tokenizer::TokenKind::Word {
                        let upper = tokens[j].text.to_uppercase();
                        if upper == "ON" || upper == "USING" {
                            found_on = true;
                            break;
                        }
                        // Hit another clause → ON is missing
                        if matches!(
                            upper.as_str(),
                            "JOIN"
                                | "LEFT"
                                | "RIGHT"
                                | "INNER"
                                | "FULL"
                                | "CROSS"
                                | "NATURAL"
                                | "WHERE"
                                | "ORDER"
                                | "GROUP"
                                | "HAVING"
                                | "LIMIT"
                                | "UNION"
                                | "INTERSECT"
                                | "EXCEPT"
                        ) {
                            break;
                        }
                    }
                    j += 1;
                }

                // CROSS JOIN and NATURAL JOIN don't need ON
                let is_cross_or_natural = if i > 0 {
                    let mut k = i - 1;
                    while k > 0 && tokens[k].kind == tokenizer::TokenKind::Whitespace {
                        k -= 1;
                    }
                    tokens[k].kind == tokenizer::TokenKind::Word
                        && matches!(tokens[k].text.to_uppercase().as_str(), "CROSS" | "NATURAL")
                } else {
                    false
                };

                if !found_on && !is_cross_or_natural {
                    out.push(Diagnostic {
                        row: join_token.row,
                        col_start: join_token.col,
                        col_end: join_token.col + join_token.text.len(),
                        message: "JOIN without ON clause".to_string(),
                        severity: DiagnosticSeverity::Warning,
                        source: DiagnosticSource::Lint,
                    });
                }
            }
            i += 1;
        }
    }

    /// Suggest a similar name from metadata when a table/schema/column is unknown.
    fn suggest_similar(&self, error_msg: &str, kind: &ResolutionErrorKind) -> Option<String> {
        use crate::sql_engine::completion::fuzzy_match;
        use crate::sql_engine::metadata::ObjectKind;

        // Extract the unknown name from the error message
        let name = error_msg
            .strip_prefix("Unknown table '")
            .or_else(|| error_msg.strip_prefix("Unknown schema '"))
            .or_else(|| error_msg.strip_prefix("Unknown column '"))
            .and_then(|s| s.strip_suffix('\''))?;

        let candidates: Vec<String> = match kind {
            ResolutionErrorKind::UnknownTable => {
                let kinds = &[ObjectKind::Table, ObjectKind::View];
                self.metadata
                    .objects_by_kind(None, kinds)
                    .iter()
                    .map(|e| e.display_name.clone())
                    .collect()
            }
            ResolutionErrorKind::UnknownSchema => self
                .metadata
                .all_schemas()
                .iter()
                .map(|s| s.to_string())
                .collect(),
            _ => return None,
        };

        // Find the best fuzzy match with a reasonable threshold
        let mut best: Option<(String, i32)> = None;
        for candidate in &candidates {
            if let Some(m) = fuzzy_match(name, candidate)
                && m.score > 200
                && best.as_ref().is_none_or(|(_, s)| m.score > *s)
            {
                best = Some((candidate.clone(), m.score));
            }
        }
        best.map(|(name, _)| name)
    }
}

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

/// Parse line/column from sqlparser error messages.
/// Format: "Expected ..., found: ... at Line: 5, Column: 10"
fn parse_syntax_error_position(msg: &str) -> (usize, usize) {
    let mut line = 1;
    let mut col = 1;
    if let Some(pos) = msg.find("Line: ")
        && let Some(num_str) = msg[pos + 6..].split(',').next()
    {
        line = num_str.trim().parse().unwrap_or(1);
    }
    if let Some(pos) = msg.find("Column: ")
        && let Some(num_str) = msg[pos + 8..].split(|c: char| !c.is_ascii_digit()).next()
    {
        col = num_str.trim().parse().unwrap_or(1);
    }
    (line, col)
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;
    use crate::sql_engine::dialect::OracleDialect;
    use crate::sql_engine::metadata::{MetadataIndex, ObjectKind};
    use crate::sql_engine::models::ResolvedColumn;

    fn test_index() -> MetadataIndex {
        let mut idx = MetadataIndex::new();
        idx.set_db_type(crate::core::models::DatabaseType::Oracle);
        idx.set_current_schema("HR");
        idx.add_schema("HR");
        idx.add_object("HR", "EMPLOYEES", ObjectKind::Table);
        idx.add_object("HR", "DEPARTMENTS", ObjectKind::Table);

        idx.cache_columns(
            "HR",
            "EMPLOYEES",
            vec![ResolvedColumn {
                name: "EMPLOYEE_ID".into(),
                data_type: "NUMBER".into(),
                nullable: false,
                is_primary_key: true,
                table_schema: "HR".into(),
                table_name: "EMPLOYEES".into(),
            }],
        );
        idx
    }

    // -- DiagnosticSet tests --

    #[test]
    fn diagnostic_set_update_source_preserves_others() {
        let mut set = DiagnosticSet::new();
        set.update_source(
            DiagnosticSource::Syntax,
            vec![Diagnostic {
                row: 0,
                col_start: 0,
                col_end: 5,
                message: "syntax err".into(),
                severity: DiagnosticSeverity::Error,
                source: DiagnosticSource::Syntax,
            }],
        );
        set.update_source(
            DiagnosticSource::Lint,
            vec![Diagnostic {
                row: 1,
                col_start: 0,
                col_end: 8,
                message: "SELECT *".into(),
                severity: DiagnosticSeverity::Warning,
                source: DiagnosticSource::Lint,
            }],
        );
        assert_eq!(set.items().len(), 2);
        assert_eq!(set.error_count(), 1);
        assert_eq!(set.warning_count(), 1);

        // Replace syntax: keeps lint
        set.update_source(DiagnosticSource::Syntax, vec![]);
        assert_eq!(set.items().len(), 1);
        assert_eq!(set.items()[0].source, DiagnosticSource::Lint);
    }

    #[test]
    fn diagnostic_set_clear() {
        let mut set = DiagnosticSet::new();
        let gen_before = set.generation();
        set.update_source(
            DiagnosticSource::Syntax,
            vec![Diagnostic {
                row: 0,
                col_start: 0,
                col_end: 1,
                message: "err".into(),
                severity: DiagnosticSeverity::Error,
                source: DiagnosticSource::Syntax,
            }],
        );
        set.clear();
        assert!(set.is_empty());
        assert!(set.generation() > gen_before);
    }

    #[test]
    fn diagnostic_set_sorted_by_position() {
        let mut set = DiagnosticSet::new();
        set.update_source(
            DiagnosticSource::Lint,
            vec![
                Diagnostic {
                    row: 2,
                    col_start: 0,
                    col_end: 1,
                    message: "b".into(),
                    severity: DiagnosticSeverity::Warning,
                    source: DiagnosticSource::Lint,
                },
                Diagnostic {
                    row: 0,
                    col_start: 5,
                    col_end: 6,
                    message: "a".into(),
                    severity: DiagnosticSeverity::Warning,
                    source: DiagnosticSource::Lint,
                },
            ],
        );
        assert_eq!(set.items()[0].row, 0);
        assert_eq!(set.items()[1].row, 2);
    }

    // -- Syntax pass tests --

    #[test]
    fn syntax_error_detected() {
        let idx = test_index();
        let dialect = OracleDialect;
        let provider = DiagnosticProvider::new(&dialect, &idx);

        let lines: Vec<String> = vec!["SELEC * FROM employees".into()];
        let diags = provider.check_local(&lines);

        let syntax_errs: Vec<&Diagnostic> = diags
            .iter()
            .filter(|d| d.source == DiagnosticSource::Syntax)
            .collect();
        assert!(!syntax_errs.is_empty());
        assert_eq!(syntax_errs[0].severity, DiagnosticSeverity::Error);
    }

    #[test]
    fn valid_sql_no_syntax_error() {
        let idx = test_index();
        let dialect = OracleDialect;
        let provider = DiagnosticProvider::new(&dialect, &idx);

        let lines: Vec<String> = vec!["SELECT * FROM employees".into()];
        let diags = provider.check_local(&lines);

        let syntax_errs: Vec<&Diagnostic> = diags
            .iter()
            .filter(|d| d.source == DiagnosticSource::Syntax)
            .collect();
        assert!(syntax_errs.is_empty());
    }

    // -- Semantic pass tests --

    #[test]
    fn unknown_table_semantic_error() {
        let idx = test_index();
        let dialect = OracleDialect;
        let provider = DiagnosticProvider::new(&dialect, &idx);

        let lines: Vec<String> = vec!["SELECT * FROM nonexistent_table".into()];
        let diags = provider.check_local(&lines);

        let sem_errs: Vec<&Diagnostic> = diags
            .iter()
            .filter(|d| d.source == DiagnosticSource::Semantic)
            .collect();
        assert!(!sem_errs.is_empty());
        assert!(sem_errs[0].message.contains("Unknown table"));
    }

    #[test]
    fn known_table_no_semantic_error() {
        let idx = test_index();
        let dialect = OracleDialect;
        let provider = DiagnosticProvider::new(&dialect, &idx);

        let lines: Vec<String> = vec!["SELECT * FROM employees".into()];
        let diags = provider.check_local(&lines);

        let sem_errs: Vec<&Diagnostic> = diags
            .iter()
            .filter(|d| d.source == DiagnosticSource::Semantic)
            .collect();
        assert!(sem_errs.is_empty());
    }

    // -- Lint pass tests --

    #[test]
    fn lint_select_star_warning() {
        let idx = test_index();
        let dialect = OracleDialect;
        let provider = DiagnosticProvider::new(&dialect, &idx);

        let lines: Vec<String> = vec!["SELECT * FROM employees".into()];
        let diags = provider.check_local(&lines);

        let lint_warns: Vec<&Diagnostic> = diags
            .iter()
            .filter(|d| d.source == DiagnosticSource::Lint && d.message.contains("SELECT *"))
            .collect();
        assert_eq!(lint_warns.len(), 1);
        assert_eq!(lint_warns[0].severity, DiagnosticSeverity::Warning);
    }

    #[test]
    fn lint_no_warning_for_named_columns() {
        let idx = test_index();
        let dialect = OracleDialect;
        let provider = DiagnosticProvider::new(&dialect, &idx);

        let lines: Vec<String> = vec!["SELECT employee_id FROM employees".into()];
        let diags = provider.check_local(&lines);

        let lint_star: Vec<&Diagnostic> = diags
            .iter()
            .filter(|d| d.source == DiagnosticSource::Lint && d.message.contains("SELECT *"))
            .collect();
        assert!(lint_star.is_empty());
    }

    #[test]
    fn lint_delete_without_where() {
        let idx = test_index();
        let dialect = OracleDialect;
        let provider = DiagnosticProvider::new(&dialect, &idx);

        let lines: Vec<String> = vec!["DELETE FROM employees".into()];
        let diags = provider.check_local(&lines);

        let lint_warns: Vec<&Diagnostic> = diags
            .iter()
            .filter(|d| d.source == DiagnosticSource::Lint && d.message.contains("without WHERE"))
            .collect();
        assert!(!lint_warns.is_empty());
    }

    #[test]
    fn lint_update_without_where() {
        let idx = test_index();
        let dialect = OracleDialect;
        let provider = DiagnosticProvider::new(&dialect, &idx);

        let lines: Vec<String> = vec!["UPDATE employees SET name = 'x'".into()];
        let diags = provider.check_local(&lines);

        let lint_warns: Vec<&Diagnostic> = diags
            .iter()
            .filter(|d| d.source == DiagnosticSource::Lint && d.message.contains("without WHERE"))
            .collect();
        assert!(!lint_warns.is_empty());
    }

    #[test]
    fn lint_no_warning_with_where() {
        let idx = test_index();
        let dialect = OracleDialect;
        let provider = DiagnosticProvider::new(&dialect, &idx);

        let lines: Vec<String> = vec!["DELETE FROM employees WHERE id = 1".into()];
        let diags = provider.check_local(&lines);

        let lint_warns: Vec<&Diagnostic> = diags
            .iter()
            .filter(|d| d.source == DiagnosticSource::Lint && d.message.contains("without WHERE"))
            .collect();
        assert!(lint_warns.is_empty());
    }

    #[test]
    fn lint_join_without_on() {
        let idx = test_index();
        let dialect = OracleDialect;
        let provider = DiagnosticProvider::new(&dialect, &idx);

        let lines: Vec<String> = vec!["SELECT * FROM employees JOIN departments WHERE 1=1".into()];
        let diags = provider.check_local(&lines);

        let lint_warns: Vec<&Diagnostic> = diags
            .iter()
            .filter(|d| d.source == DiagnosticSource::Lint && d.message.contains("JOIN without ON"))
            .collect();
        assert!(!lint_warns.is_empty());
    }

    #[test]
    fn lint_join_with_on_no_warning() {
        let idx = test_index();
        let dialect = OracleDialect;
        let provider = DiagnosticProvider::new(&dialect, &idx);

        let lines: Vec<String> =
            vec!["SELECT * FROM employees e JOIN departments d ON e.dept_id = d.id".into()];
        let diags = provider.check_local(&lines);

        let lint_warns: Vec<&Diagnostic> = diags
            .iter()
            .filter(|d| d.source == DiagnosticSource::Lint && d.message.contains("JOIN without ON"))
            .collect();
        assert!(lint_warns.is_empty());
    }

    #[test]
    fn lint_cross_join_no_warning() {
        let idx = test_index();
        let dialect = OracleDialect;
        let provider = DiagnosticProvider::new(&dialect, &idx);

        let lines: Vec<String> = vec!["SELECT * FROM employees CROSS JOIN departments".into()];
        let diags = provider.check_local(&lines);

        let lint_warns: Vec<&Diagnostic> = diags
            .iter()
            .filter(|d| d.source == DiagnosticSource::Lint && d.message.contains("JOIN without ON"))
            .collect();
        assert!(lint_warns.is_empty());
    }

    // -- Multi-pass integration --

    #[test]
    fn all_three_passes_produce_results() {
        let idx = test_index();
        let dialect = OracleDialect;
        let provider = DiagnosticProvider::new(&dialect, &idx);

        // This SQL has: syntax error (SELEC), and if it parsed,
        // would have SELECT * lint warning. But syntax error stops parsing.
        // Let's use valid SQL that triggers multiple passes:
        let lines: Vec<String> = vec!["DELETE * FROM nonexistent".into()];
        let diags = provider.check_local(&lines);

        // Should have: syntax error (DELETE *), semantic error (nonexistent),
        // and/or lint warnings depending on what parses
        assert!(!diags.is_empty());
    }

    #[test]
    fn multiple_query_blocks_validated_independently() {
        let idx = test_index();
        let dialect = OracleDialect;
        let provider = DiagnosticProvider::new(&dialect, &idx);

        let lines: Vec<String> = vec![
            "SELECT * FROM employees".into(),
            "".into(),
            "SELEC * FROM departments".into(),
        ];
        let diags = provider.check_local(&lines);

        // First block: valid syntax, but has SELECT * lint warning
        // Second block: syntax error
        let syntax_errs: Vec<&Diagnostic> = diags
            .iter()
            .filter(|d| d.source == DiagnosticSource::Syntax)
            .collect();
        assert!(!syntax_errs.is_empty());
        // Syntax error should be on row 2 (the "SELEC" line)
        assert_eq!(syntax_errs[0].row, 2);
    }
}