flowscope-core 0.7.0

Core SQL lineage analysis engine
Documentation
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
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
//! LINT_ST_009: Reversed JOIN condition ordering.
//!
//! Detect predicates where the newly joined relation appears on the left side
//! and prior relation on the right side (e.g. `o.user_id = u.id`).

use crate::linter::config::LintConfig;
use crate::linter::rule::{LintContext, LintRule};
use crate::types::{issue_codes, Issue, IssueAutofixApplicability, IssuePatchEdit, Span};
use sqlparser::ast::{BinaryOperator, Expr, Spanned, Statement, TableFactor};

use super::semantic_helpers::{
    join_on_expr, table_factor_reference_name, visit_selects_in_statement,
};

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum PreferredFirstTableInJoinClause {
    Earlier,
    Later,
}

impl PreferredFirstTableInJoinClause {
    fn from_config(config: &LintConfig) -> Self {
        match config
            .rule_option_str(
                issue_codes::LINT_ST_009,
                "preferred_first_table_in_join_clause",
            )
            .unwrap_or("earlier")
            .to_ascii_lowercase()
            .as_str()
        {
            "later" => Self::Later,
            _ => Self::Earlier,
        }
    }

    fn left_source<'a>(self, current: &'a str, previous: &'a str) -> &'a str {
        match self {
            Self::Earlier => current,
            Self::Later => previous,
        }
    }

    fn right_source<'a>(self, current: &'a str, previous: &'a str) -> &'a str {
        match self {
            Self::Earlier => previous,
            Self::Later => current,
        }
    }
}

pub struct StructureJoinConditionOrder {
    preferred_first_table: PreferredFirstTableInJoinClause,
}

impl StructureJoinConditionOrder {
    pub fn from_config(config: &LintConfig) -> Self {
        Self {
            preferred_first_table: PreferredFirstTableInJoinClause::from_config(config),
        }
    }
}

impl Default for StructureJoinConditionOrder {
    fn default() -> Self {
        Self {
            preferred_first_table: PreferredFirstTableInJoinClause::Earlier,
        }
    }
}

impl LintRule for StructureJoinConditionOrder {
    fn code(&self) -> &'static str {
        issue_codes::LINT_ST_009
    }

    fn name(&self) -> &'static str {
        "Structure join condition order"
    }

    fn description(&self) -> &'static str {
        "Joins should list the table referenced earlier/later first."
    }

    fn check(&self, statement: &Statement, ctx: &LintContext) -> Vec<Issue> {
        let mut issues = Vec::new();

        visit_selects_in_statement(statement, &mut |select| {
            // SQLFluff ST09 parity: report at most one reversed-join issue
            // per SELECT, matching SQLFluff's first-violation-only behaviour.
            let before = issues.len();
            'from_loop: for table in &select.from {
                let mut seen_sources: Vec<String> = Vec::new();
                check_table_factor_joins(
                    &table.relation,
                    &table.joins,
                    &mut seen_sources,
                    self.preferred_first_table,
                    ctx,
                    &mut issues,
                );
                if issues.len() > before {
                    break 'from_loop;
                }
            }
        });

        issues
    }
}

fn check_table_factor_joins(
    relation: &TableFactor,
    joins: &[sqlparser::ast::Join],
    seen_sources: &mut Vec<String>,
    preference: PreferredFirstTableInJoinClause,
    ctx: &LintContext,
    issues: &mut Vec<Issue>,
) {
    let issues_before = issues.len();

    // For NestedJoin, recurse into the inner table_with_joins.
    if let TableFactor::NestedJoin {
        table_with_joins, ..
    } = relation
    {
        check_table_factor_joins(
            &table_with_joins.relation,
            &table_with_joins.joins,
            seen_sources,
            preference,
            ctx,
            issues,
        );
    } else if let Some(base) = table_factor_reference_name(relation) {
        seen_sources.push(base);
    }

    for (join_index, join) in joins.iter().enumerate() {
        // Recurse into nested join relations on the right side.
        if let TableFactor::NestedJoin {
            table_with_joins, ..
        } = &join.relation
        {
            check_table_factor_joins(
                &table_with_joins.relation,
                &table_with_joins.joins,
                seen_sources,
                preference,
                ctx,
                issues,
            );
        }

        let join_name = table_factor_reference_name(&join.relation);
        if let (Some(current), Some(on_expr)) =
            (join_name.as_ref(), join_on_expr(&join.join_operator))
        {
            // SQLFluff parity: only flag the first reversed join per FROM clause.
            if issues.len() == issues_before {
                let matching_previous = seen_sources
                    .iter()
                    .rev()
                    .find(|candidate| {
                        let left = preference.left_source(current, candidate.as_str());
                        let right = preference.right_source(current, candidate.as_str());
                        has_join_pair(on_expr, left, right)
                    })
                    .cloned();

                if matching_previous.is_some() {
                    let mut issue_span = expr_statement_offsets(ctx, on_expr)
                        .map(|(expr_start, expr_end)| {
                            ctx.span_from_statement_offset(expr_start, expr_end)
                        })
                        .unwrap_or_else(|| Span::new(0, 0));
                    let mut edits: Vec<IssuePatchEdit> = Vec::new();

                    if let Some((span, replacement)) =
                        join_condition_autofix_for_sources(ctx, on_expr, current, seen_sources)
                    {
                        issue_span = span;
                        edits.push(IssuePatchEdit::new(span, replacement));
                    }

                    let mut seen_for_following = seen_sources.clone();
                    if let Some(name) = join_name.as_ref() {
                        seen_for_following.push(name.clone());
                    }
                    edits.extend(collect_following_join_autofixes(
                        &joins[join_index + 1..],
                        &seen_for_following,
                        preference,
                        ctx,
                    ));

                    if issue_span.start != issue_span.end {
                        let mut issue = Issue::info(
                            issue_codes::LINT_ST_009,
                            "Join condition ordering appears inconsistent with configured preference.",
                        )
                        .with_statement(ctx.statement_index)
                        .with_span(issue_span);
                        if !edits.is_empty() {
                            issue =
                                issue.with_autofix_edits(IssueAutofixApplicability::Safe, edits);
                        }
                        issues.push(issue);
                    }
                }
            }
        }

        if let Some(name) = join_name {
            seen_sources.push(name);
        }
    }
}

fn collect_following_join_autofixes(
    joins: &[sqlparser::ast::Join],
    seen_sources: &[String],
    preference: PreferredFirstTableInJoinClause,
    ctx: &LintContext,
) -> Vec<IssuePatchEdit> {
    let mut seen = seen_sources.to_vec();
    let mut edits = Vec::new();

    for join in joins {
        let join_name = table_factor_reference_name(&join.relation);
        if let (Some(current), Some(on_expr)) =
            (join_name.as_ref(), join_on_expr(&join.join_operator))
        {
            let matching_previous = seen
                .iter()
                .rev()
                .find(|candidate| {
                    let left = preference.left_source(current, candidate.as_str());
                    let right = preference.right_source(current, candidate.as_str());
                    has_join_pair(on_expr, left, right)
                })
                .cloned();
            if matching_previous.is_some() {
                if let Some((span, replacement)) =
                    join_condition_autofix_for_sources(ctx, on_expr, current, &seen)
                {
                    edits.push(IssuePatchEdit::new(span, replacement));
                }
            }
        }
        if let Some(name) = join_name {
            seen.push(name);
        }
    }

    edits
}

fn is_comparison_operator(op: &BinaryOperator) -> bool {
    matches!(
        op,
        BinaryOperator::Eq
            | BinaryOperator::NotEq
            | BinaryOperator::Lt
            | BinaryOperator::Gt
            | BinaryOperator::LtEq
            | BinaryOperator::GtEq
            | BinaryOperator::Spaceship
    )
}

fn has_join_pair(expr: &Expr, left_source_name: &str, right_source_name: &str) -> bool {
    match expr {
        Expr::BinaryOp { left, op, right } => {
            let direct = if is_comparison_operator(op) {
                if let (Some(left_prefix), Some(right_prefix)) =
                    (expr_qualified_prefix(left), expr_qualified_prefix(right))
                {
                    left_prefix == left_source_name && right_prefix == right_source_name
                } else {
                    false
                }
            } else {
                false
            };

            direct
                || has_join_pair(left, left_source_name, right_source_name)
                || has_join_pair(right, left_source_name, right_source_name)
        }
        Expr::UnaryOp { expr: inner, .. }
        | Expr::Nested(inner)
        | Expr::IsNull(inner)
        | Expr::IsNotNull(inner)
        | Expr::Cast { expr: inner, .. } => {
            has_join_pair(inner, left_source_name, right_source_name)
        }
        Expr::InList { expr, list, .. } => {
            has_join_pair(expr, left_source_name, right_source_name)
                || list
                    .iter()
                    .any(|item| has_join_pair(item, left_source_name, right_source_name))
        }
        Expr::Between {
            expr, low, high, ..
        } => {
            has_join_pair(expr, left_source_name, right_source_name)
                || has_join_pair(low, left_source_name, right_source_name)
                || has_join_pair(high, left_source_name, right_source_name)
        }
        Expr::Case {
            operand,
            conditions,
            else_result,
            ..
        } => {
            operand
                .as_ref()
                .is_some_and(|operand| has_join_pair(operand, left_source_name, right_source_name))
                || conditions.iter().any(|when| {
                    has_join_pair(&when.condition, left_source_name, right_source_name)
                        || has_join_pair(&when.result, left_source_name, right_source_name)
                })
                || else_result.as_ref().is_some_and(|otherwise| {
                    has_join_pair(otherwise, left_source_name, right_source_name)
                })
        }
        _ => false,
    }
}

/// Produce source-text-level edits that swap individual reversed comparison
/// pairs while preserving original formatting, quoting, and keyword casing.
fn join_condition_autofix_for_sources(
    ctx: &LintContext,
    on_expr: &Expr,
    current_source: &str,
    previous_sources: &[String],
) -> Option<(Span, String)> {
    if previous_sources.is_empty() {
        return None;
    }
    let sql = ctx.statement_sql();
    let (expr_start, expr_end) = expr_statement_offsets(ctx, on_expr)?;
    if expr_start > expr_end || expr_end > sql.len() {
        return None;
    }
    let expr_span = ctx.span_from_statement_offset(expr_start, expr_end);
    let expr_source = &sql[expr_start..expr_end];

    // Collect text-level edits for each reversed pair.
    let mut edits: Vec<(usize, usize, String)> = Vec::new();
    for previous_source in previous_sources {
        collect_reversed_pair_edits(ctx, on_expr, current_source, previous_source, &mut edits);
    }

    if edits.is_empty() {
        return ast_join_condition_autofix_for_sources(
            on_expr,
            expr_span,
            expr_source,
            current_source,
            previous_sources,
        );
    }

    // Sort edits by position (ascending) for deterministic application.
    edits.sort_by_key(|(start, _, _)| *start);
    edits.dedup_by(|left, right| left.0 == right.0 && left.1 == right.1 && left.2 == right.2);

    // Build replacement by applying text edits to the overall ON expression
    // source span.
    let mut result = String::with_capacity(expr_source.len());
    let mut cursor = expr_start;

    for (edit_start, edit_end, replacement) in &edits {
        if *edit_start < expr_start
            || *edit_end > expr_end
            || *edit_start > *edit_end
            || *edit_start < cursor
        {
            // Overlapping edits — bail out to avoid corruption.
            return ast_join_condition_autofix_for_sources(
                on_expr,
                expr_span,
                expr_source,
                current_source,
                previous_sources,
            );
        }
        result.push_str(&sql[cursor..*edit_start]);
        result.push_str(replacement);
        cursor = *edit_end;
    }
    if cursor > expr_end {
        return ast_join_condition_autofix_for_sources(
            on_expr,
            expr_span,
            expr_source,
            current_source,
            previous_sources,
        );
    }
    result.push_str(&sql[cursor..expr_end]);

    Some((expr_span, result))
}

fn ast_join_condition_autofix_for_sources(
    on_expr: &Expr,
    expr_span: Span,
    expr_source: &str,
    current_source: &str,
    previous_sources: &[String],
) -> Option<(Span, String)> {
    // AST rendering would drop comments; avoid this fallback on commented ON clauses.
    if expr_source.contains("--") || expr_source.contains("/*") {
        return None;
    }
    if previous_sources.is_empty() {
        return None;
    }

    let mut rewritten = on_expr.clone();
    let mut changed = false;
    for previous_source in previous_sources {
        changed |= swap_reversed_pairs_ast(&mut rewritten, current_source, previous_source);
    }
    if !changed {
        return None;
    }
    let replacement = rewritten.to_string();
    if replacement == expr_source {
        return None;
    }
    Some((expr_span, replacement))
}

fn swap_reversed_pairs_ast(expr: &mut Expr, current_source: &str, previous_source: &str) -> bool {
    match expr {
        Expr::BinaryOp { left, op, right } => {
            if is_comparison_operator(op) {
                let left_prefix = expr_qualified_prefix(left);
                let right_prefix = expr_qualified_prefix(right);
                if left_prefix.as_deref() == Some(current_source)
                    && right_prefix.as_deref() == Some(previous_source)
                {
                    std::mem::swap(left, right);
                    *op = flipped_comparison_operator(op);
                    return true;
                }
            }

            let left_changed = swap_reversed_pairs_ast(left, current_source, previous_source);
            let right_changed = swap_reversed_pairs_ast(right, current_source, previous_source);
            left_changed || right_changed
        }
        Expr::UnaryOp { expr: inner, .. }
        | Expr::Nested(inner)
        | Expr::IsNull(inner)
        | Expr::IsNotNull(inner)
        | Expr::IsTrue(inner)
        | Expr::IsNotTrue(inner)
        | Expr::IsFalse(inner)
        | Expr::IsNotFalse(inner)
        | Expr::IsUnknown(inner)
        | Expr::IsNotUnknown(inner)
        | Expr::Cast { expr: inner, .. } => {
            swap_reversed_pairs_ast(inner, current_source, previous_source)
        }
        Expr::InList {
            expr: target, list, ..
        } => {
            let mut changed = swap_reversed_pairs_ast(target, current_source, previous_source);
            for item in list {
                changed |= swap_reversed_pairs_ast(item, current_source, previous_source);
            }
            changed
        }
        Expr::Between {
            expr: target,
            low,
            high,
            ..
        } => {
            swap_reversed_pairs_ast(target, current_source, previous_source)
                | swap_reversed_pairs_ast(low, current_source, previous_source)
                | swap_reversed_pairs_ast(high, current_source, previous_source)
        }
        Expr::Case {
            operand,
            conditions,
            else_result,
            ..
        } => {
            let mut changed = false;
            if let Some(operand) = operand {
                changed |= swap_reversed_pairs_ast(operand, current_source, previous_source);
            }
            for case_when in conditions {
                changed |= swap_reversed_pairs_ast(
                    &mut case_when.condition,
                    current_source,
                    previous_source,
                );
                changed |=
                    swap_reversed_pairs_ast(&mut case_when.result, current_source, previous_source);
            }
            if let Some(else_result) = else_result {
                changed |= swap_reversed_pairs_ast(else_result, current_source, previous_source);
            }
            changed
        }
        _ => false,
    }
}

fn flipped_comparison_operator(op: &BinaryOperator) -> BinaryOperator {
    match op {
        BinaryOperator::Lt => BinaryOperator::Gt,
        BinaryOperator::Gt => BinaryOperator::Lt,
        BinaryOperator::LtEq => BinaryOperator::GtEq,
        BinaryOperator::GtEq => BinaryOperator::LtEq,
        _ => op.clone(),
    }
}

/// Walk the AST and collect source-text edits for each reversed comparison
/// pair. Each edit replaces `left op right` with `right flipped_op left`
/// using the original source text for both operands.
fn collect_reversed_pair_edits(
    ctx: &LintContext,
    expr: &Expr,
    current_source: &str,
    previous_source: &str,
    edits: &mut Vec<(usize, usize, String)>,
) {
    let sql = ctx.statement_sql();

    match expr {
        Expr::BinaryOp { left, op, right } => {
            if is_comparison_operator(op) {
                let left_prefix = expr_qualified_prefix(left);
                let right_prefix = expr_qualified_prefix(right);
                if left_prefix.as_deref() == Some(current_source)
                    && right_prefix.as_deref() == Some(previous_source)
                {
                    // Extract source text for left and right operands.
                    if let (Some((l_start, l_end)), Some((r_start, r_end))) = (
                        expr_statement_offsets(ctx, left),
                        expr_statement_offsets(ctx, right),
                    ) {
                        if l_start <= l_end
                            && l_end <= r_start
                            && r_start <= r_end
                            && r_end <= sql.len()
                        {
                            let gap = &sql[l_end..r_start];
                            // Skip if the gap contains a comment — swapping could
                            // misplace or corrupt it.
                            if gap.contains("--") || gap.contains("/*") {
                                return;
                            }
                            let left_text = &sql[l_start..l_end];
                            let right_text = &sql[r_start..r_end];
                            let op_text = flip_operator_text(gap, op);

                            // Replace the entire `left op right` span with `right op left`.
                            let replacement = format!("{right_text}{op_text}{left_text}");
                            edits.push((l_start, r_end, replacement));
                            return; // Don't recurse into children we just handled.
                        }
                    }
                }
            }

            // Recurse into children for logical connectives (AND, OR).
            collect_reversed_pair_edits(ctx, left, current_source, previous_source, edits);
            collect_reversed_pair_edits(ctx, right, current_source, previous_source, edits);
        }
        Expr::UnaryOp { expr: inner, .. }
        | Expr::Nested(inner)
        | Expr::IsNull(inner)
        | Expr::IsNotNull(inner)
        | Expr::IsTrue(inner)
        | Expr::IsNotTrue(inner)
        | Expr::IsFalse(inner)
        | Expr::IsNotFalse(inner)
        | Expr::IsUnknown(inner)
        | Expr::IsNotUnknown(inner)
        | Expr::Cast { expr: inner, .. } => {
            collect_reversed_pair_edits(ctx, inner, current_source, previous_source, edits)
        }
        Expr::InList {
            expr: target, list, ..
        } => {
            collect_reversed_pair_edits(ctx, target, current_source, previous_source, edits);
            for item in list {
                collect_reversed_pair_edits(ctx, item, current_source, previous_source, edits);
            }
        }
        Expr::Between {
            expr: target,
            low,
            high,
            ..
        } => {
            collect_reversed_pair_edits(ctx, target, current_source, previous_source, edits);
            collect_reversed_pair_edits(ctx, low, current_source, previous_source, edits);
            collect_reversed_pair_edits(ctx, high, current_source, previous_source, edits);
        }
        Expr::Case {
            operand,
            conditions,
            else_result,
            ..
        } => {
            if let Some(operand) = operand {
                collect_reversed_pair_edits(ctx, operand, current_source, previous_source, edits);
            }
            for case_when in conditions {
                collect_reversed_pair_edits(
                    ctx,
                    &case_when.condition,
                    current_source,
                    previous_source,
                    edits,
                );
                collect_reversed_pair_edits(
                    ctx,
                    &case_when.result,
                    current_source,
                    previous_source,
                    edits,
                );
            }
            if let Some(else_result) = else_result {
                collect_reversed_pair_edits(
                    ctx,
                    else_result,
                    current_source,
                    previous_source,
                    edits,
                );
            }
        }
        _ => {}
    }
}

/// Given the source text between the left and right operands (which contains
/// whitespace + operator + whitespace), return it with the operator flipped
/// for directional comparison operators.
fn flip_operator_text(gap: &str, op: &BinaryOperator) -> String {
    match op {
        // Symmetric operators — no change needed.
        BinaryOperator::Eq | BinaryOperator::NotEq | BinaryOperator::Spaceship => gap.to_string(),
        // Directional operators — flip the operator while preserving surrounding whitespace.
        BinaryOperator::Lt => gap.replacen('<', ">", 1),
        BinaryOperator::Gt => gap.replacen('>', "<", 1),
        BinaryOperator::LtEq => gap.replacen("<=", ">=", 1),
        BinaryOperator::GtEq => gap.replacen(">=", "<=", 1),
        _ => gap.to_string(),
    }
}

fn expr_statement_offsets(ctx: &LintContext, expr: &Expr) -> Option<(usize, usize)> {
    // Statement ranges may intentionally trim leading comments/whitespace.
    // SQLParser span line/column coordinates are often absolute to the
    // original document, so prefer document-level offset conversion when the
    // statement does not start at byte 0.
    if ctx.statement_range.start > 0 {
        if let Some((start, end)) = expr_span_offsets(ctx.sql, expr) {
            if start >= ctx.statement_range.start && end <= ctx.statement_range.end {
                return Some((
                    start - ctx.statement_range.start,
                    end - ctx.statement_range.start,
                ));
            }
        }
    }

    if let Some((start, end)) = expr_span_offsets(ctx.statement_sql(), expr) {
        return Some((start, end));
    }

    let (start, end) = expr_span_offsets(ctx.sql, expr)?;
    if start < ctx.statement_range.start || end > ctx.statement_range.end {
        return None;
    }
    Some((
        start - ctx.statement_range.start,
        end - ctx.statement_range.start,
    ))
}

fn expr_span_offsets(sql: &str, expr: &Expr) -> Option<(usize, usize)> {
    let span = expr.span();
    if span.start.line == 0 || span.start.column == 0 || span.end.line == 0 || span.end.column == 0
    {
        return None;
    }

    let start = line_col_to_offset(sql, span.start.line as usize, span.start.column as usize)?;
    let end = line_col_to_offset(sql, span.end.line as usize, span.end.column as usize)?;
    (end >= start).then_some((start, end))
}

fn line_col_to_offset(sql: &str, line: usize, column: usize) -> Option<usize> {
    if line == 0 || column == 0 {
        return None;
    }

    let mut current_line = 1usize;
    let mut line_start = 0usize;

    for (idx, ch) in sql.char_indices() {
        if current_line == line {
            break;
        }
        if ch == '\n' {
            current_line += 1;
            line_start = idx + ch.len_utf8();
        }
    }
    if current_line != line {
        return None;
    }

    let mut current_column = 1usize;
    for (rel_idx, ch) in sql[line_start..].char_indices() {
        if current_column == column {
            return Some(line_start + rel_idx);
        }
        if ch == '\n' {
            return None;
        }
        current_column += 1;
    }

    if current_column == column {
        return Some(sql.len());
    }

    None
}

fn normalize_source_name(name: &str) -> String {
    name.trim_matches(|ch| matches!(ch, '"' | '`' | '\'' | '[' | ']'))
        .to_ascii_uppercase()
}

fn expr_qualified_prefix(expr: &Expr) -> Option<String> {
    match expr {
        Expr::CompoundIdentifier(parts) if parts.len() > 1 => parts
            .get(parts.len().saturating_sub(2))
            .map(|ident| normalize_source_name(&ident.value)),
        Expr::Nested(inner)
        | Expr::UnaryOp { expr: inner, .. }
        | Expr::Cast { expr: inner, .. } => expr_qualified_prefix(inner),
        _ => None,
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::parser::parse_sql;
    use crate::types::{IssueAutofixApplicability, IssuePatchEdit};

    fn run(sql: &str) -> Vec<Issue> {
        let statements = parse_sql(sql).expect("parse");
        let rule = StructureJoinConditionOrder::default();
        statements
            .iter()
            .enumerate()
            .flat_map(|(index, statement)| {
                rule.check(
                    statement,
                    &LintContext {
                        sql,
                        statement_range: 0..sql.len(),
                        statement_index: index,
                    },
                )
            })
            .collect()
    }

    fn apply_edits(sql: &str, edits: &[IssuePatchEdit]) -> String {
        let mut output = sql.to_string();
        let mut ordered = edits.iter().collect::<Vec<_>>();
        ordered.sort_by_key(|edit| edit.span.start);

        for edit in ordered.into_iter().rev() {
            output.replace_range(edit.span.start..edit.span.end, &edit.replacement);
        }

        output
    }

    // --- Edge cases adopted from sqlfluff ST09 ---

    #[test]
    fn allows_queries_without_joins() {
        let issues = run("select * from foo");
        assert!(issues.is_empty());
    }

    #[test]
    fn allows_expected_source_order_in_join_condition() {
        let issues = run("select foo.a, bar.b from foo left join bar on foo.a = bar.a");
        assert!(issues.is_empty());
    }

    #[test]
    fn flags_reversed_source_order_in_join_condition() {
        let issues = run("select foo.a, bar.b from foo left join bar on bar.a = foo.a");
        assert_eq!(issues.len(), 1);
        assert_eq!(issues[0].code, issue_codes::LINT_ST_009);

        let autofix = issues[0]
            .autofix
            .as_ref()
            .expect("expected ST009 core autofix metadata");
        assert_eq!(autofix.applicability, IssueAutofixApplicability::Safe);
        assert_eq!(autofix.edits.len(), 1);
        let fixed = apply_edits(
            "select foo.a, bar.b from foo left join bar on bar.a = foo.a",
            &autofix.edits,
        );
        assert_eq!(
            fixed,
            "select foo.a, bar.b from foo left join bar on foo.a = bar.a"
        );
    }

    #[test]
    fn allows_unqualified_reference_side() {
        let issues = run("select foo.a, bar.b from foo left join bar on bar.b = a");
        assert!(issues.is_empty());
    }

    #[test]
    fn flags_multiple_reversed_subconditions() {
        let issues = run(
            "select foo.a, foo.b, bar.c from foo left join bar on bar.a = foo.a and bar.b = foo.b",
        );
        assert_eq!(issues.len(), 1);
    }

    #[test]
    fn later_preference_flags_earlier_on_left_side() {
        let config = LintConfig {
            enabled: true,
            disabled_rules: vec![],
            rule_configs: std::collections::BTreeMap::from([(
                "structure.join_condition_order".to_string(),
                serde_json::json!({"preferred_first_table_in_join_clause": "later"}),
            )]),
        };
        let rule = StructureJoinConditionOrder::from_config(&config);
        let sql = "select foo.a, bar.b from foo left join bar on foo.a = bar.a";
        let statements = parse_sql(sql).expect("parse");
        let issues = rule.check(
            &statements[0],
            &LintContext {
                sql,
                statement_range: 0..sql.len(),
                statement_index: 0,
            },
        );
        assert_eq!(issues.len(), 1);
        assert_eq!(issues[0].code, issue_codes::LINT_ST_009);
    }

    #[test]
    fn comment_in_join_condition_blocks_safe_autofix_metadata() {
        let sql = "select foo.a, bar.b from foo left join bar on bar.a /*keep*/ = foo.a";
        let issues = run(sql);
        assert_eq!(issues.len(), 1);
        assert!(
            issues[0].autofix.is_none(),
            "comment-bearing join condition should not emit ST009 safe patch metadata"
        );
    }

    #[test]
    fn flags_reversed_non_equality_comparison_operators() {
        // SQLFluff: test_fail_later_table_first_multiple_comparison_operators
        let sql = "select foo.a, bar.b from foo left join bar on bar.a != foo.a and bar.b > foo.b and bar.c <= foo.c";
        let issues = run(sql);
        assert_eq!(issues.len(), 1);
        assert_eq!(issues[0].code, issue_codes::LINT_ST_009);
    }

    #[test]
    fn flags_reversed_join_inside_bracketed_from() {
        // SQLFluff: test_fail_later_table_first_brackets_after_from
        let sql = "select foo.a, bar.b from (foo left join bar on bar.a = foo.a)";
        let issues = run(sql);
        assert_eq!(issues.len(), 1);
        assert_eq!(issues[0].code, issue_codes::LINT_ST_009);
    }

    #[test]
    fn flags_spaceship_operator_reversed() {
        // SQLFluff: test_fail_sparksql_lt_eq_gt_operator
        let sql = "SELECT bt.test FROM base_table AS bt INNER JOIN second_table AS st ON st.test <=> bt.test";
        let issues = run(sql);
        assert_eq!(issues.len(), 1);
        assert_eq!(issues[0].code, issue_codes::LINT_ST_009);
    }

    #[test]
    fn autofix_preserves_parentheses_around_condition() {
        // SQLFluff: test_fail_later_table_first_brackets_after_on
        let sql = "select foo.a, bar.b from foo left join bar on (bar.a = foo.a)";
        let issues = run(sql);
        assert_eq!(issues.len(), 1);
        let fixed = apply_edits(sql, &issues[0].autofix.as_ref().unwrap().edits);
        assert_eq!(
            fixed,
            "select foo.a, bar.b from foo left join bar on (foo.a = bar.a)"
        );
    }

    #[test]
    fn autofix_preserves_multiline_formatting_and_keyword_case() {
        // SQLFluff: test_fail_later_table_first_multiple_subconditions
        let sql = "select\n    foo.a,\n    foo.b,\n    bar.c\nfrom foo\nleft join bar\n    on bar.a = foo.a\n    and bar.b = foo.b\n";
        let issues = run(sql);
        assert_eq!(issues.len(), 1);
        let fixed = apply_edits(sql, &issues[0].autofix.as_ref().unwrap().edits);
        assert_eq!(
            fixed,
            "select\n    foo.a,\n    foo.b,\n    bar.c\nfrom foo\nleft join bar\n    on foo.a = bar.a\n    and foo.b = bar.b\n"
        );
    }

    #[test]
    fn autofix_flips_directional_comparison_operators() {
        // SQLFluff: test_fail_later_table_first_multiple_comparison_operators (single join)
        let sql = "select foo.a, bar.b from foo left join bar on bar.a != foo.a and bar.b > foo.b and bar.c <= foo.c";
        let issues = run(sql);
        assert_eq!(issues.len(), 1);
        let fixed = apply_edits(sql, &issues[0].autofix.as_ref().unwrap().edits);
        assert_eq!(
            fixed,
            "select foo.a, bar.b from foo left join bar on foo.a != bar.a and foo.b < bar.b and foo.c >= bar.c"
        );
    }

    #[test]
    fn autofix_preserves_quoted_identifiers() {
        // SQLFluff: test_fail_later_table_first_quoted_table_not_columns
        let sql = "select\n    \"foo\".\"a\",\n    \"bar\".\"b\"\nfrom foo\nleft join \"bar\"\n    on \"bar\".\"a\" = \"foo\".\"a\"\n    and \"bar\".\"b\" = foo.\"b\"\n";
        let issues = run(sql);
        assert_eq!(issues.len(), 1);
        let fixed = apply_edits(sql, &issues[0].autofix.as_ref().unwrap().edits);
        assert_eq!(
            fixed,
            "select\n    \"foo\".\"a\",\n    \"bar\".\"b\"\nfrom foo\nleft join \"bar\"\n    on \"foo\".\"a\" = \"bar\".\"a\"\n    and foo.\"b\" = \"bar\".\"b\"\n"
        );
    }

    #[test]
    fn autofix_reorders_join_conditions_against_any_seen_source_in_chain() {
        // SQLFluff: ST09 flags only the first reversed join per SELECT.
        let sql = "select\n    foo.a,\n    bar.b,\n    baz.c\nfrom foo\nleft join bar\n    on bar.a != foo.a\n    and bar.b > foo.b\n    and bar.c <= foo.c\nleft join baz\n    on baz.a <> foo.a\n    and baz.b >= foo.b\n    and baz.c < foo.c\n";
        let issues = run(sql);
        // Only the first reversed join (bar) is reported per SELECT.
        assert_eq!(issues.len(), 1);
        let fixed = apply_edits(sql, &issues[0].autofix.as_ref().unwrap().edits);
        assert_eq!(
            fixed,
            "select\n    foo.a,\n    bar.b,\n    baz.c\nfrom foo\nleft join bar\n    on foo.a != bar.a\n    and foo.b < bar.b\n    and foo.c >= bar.c\nleft join baz\n    on foo.a <> baz.a\n    and foo.b <= baz.b\n    and foo.c > baz.c\n"
        );
    }

    #[test]
    fn autofix_handles_reversed_join_with_additional_same_table_filter() {
        let sql = "select wur.id from ledger.work_unit_run as wur inner join ledger.work_unit as wu on wu.id = wur.work_unit_id and wu.type = 'job'";
        let issues = run(sql);
        assert_eq!(issues.len(), 1);

        let autofix = issues[0]
            .autofix
            .as_ref()
            .expect("expected ST009 autofix metadata");
        assert_eq!(autofix.applicability, IssueAutofixApplicability::Safe);
        assert!(!autofix.edits.is_empty());

        let fixed = apply_edits(sql, &autofix.edits);
        assert!(
            fixed.contains("wur.work_unit_id = wu.id"),
            "expected reordered join predicate, got: {fixed}"
        );
        assert!(
            fixed.contains("wu.type = 'job'"),
            "expected same-table predicate to be preserved, got: {fixed}"
        );
    }

    #[test]
    fn emits_autofix_for_reversed_workspace_join_after_ordered_prior_join() {
        let sql = "select wur.id from ledger.work_unit_run as wur join ledger.work_unit as wu on wur.work_unit_id = wu.id and wu.type = 'job' inner join ledger.workspace as ws on ws.id = wu.workspace_id left join ledger.usage_line_item as uli on uli.job_run_id = wur.external_run_id";
        let issues = run(sql);
        assert_eq!(issues.len(), 1);

        let autofix = issues[0]
            .autofix
            .as_ref()
            .expect("expected ST009 autofix metadata");
        assert_eq!(autofix.applicability, IssueAutofixApplicability::Safe);

        let fixed = apply_edits(sql, &autofix.edits);
        assert!(
            fixed.contains("wu.workspace_id = ws.id"),
            "expected reordered workspace join predicate, got: {fixed}"
        );
    }

    #[test]
    fn emits_autofix_for_schema_qualified_reversed_join_condition() {
        let sql = "select ledger.work_unit_run.id from ledger.work_unit_run join ledger.work_unit on ledger.work_unit.id = ledger.work_unit_run.work_unit_id";
        let issues = run(sql);
        assert_eq!(issues.len(), 1);

        let autofix = issues[0]
            .autofix
            .as_ref()
            .expect("expected ST009 autofix metadata");
        assert_eq!(autofix.applicability, IssueAutofixApplicability::Safe);
        assert!(!autofix.edits.is_empty());

        let fixed = apply_edits(sql, &autofix.edits);
        assert_eq!(
            fixed,
            "select ledger.work_unit_run.id from ledger.work_unit_run join ledger.work_unit on ledger.work_unit_run.work_unit_id = ledger.work_unit.id"
        );
    }

    #[test]
    fn emits_autofix_for_quoted_schema_qualified_reversed_join_condition() {
        let sql = "select \"ledger\".\"work_unit_run\".\"id\" from \"ledger\".\"work_unit_run\" join \"ledger\".\"work_unit\" on \"ledger\".\"work_unit\".\"id\" = \"ledger\".\"work_unit_run\".\"work_unit_id\"";
        let issues = run(sql);
        assert_eq!(issues.len(), 1);

        let autofix = issues[0]
            .autofix
            .as_ref()
            .expect("expected ST009 autofix metadata");
        assert_eq!(autofix.applicability, IssueAutofixApplicability::Safe);
        assert!(!autofix.edits.is_empty());

        let fixed = apply_edits(sql, &autofix.edits);
        assert_eq!(
            fixed,
            "select \"ledger\".\"work_unit_run\".\"id\" from \"ledger\".\"work_unit_run\" join \"ledger\".\"work_unit\" on \"ledger\".\"work_unit_run\".\"work_unit_id\" = \"ledger\".\"work_unit\".\"id\""
        );
    }

    #[test]
    fn emits_autofix_for_reversed_join_inside_cte_with_additional_join() {
        let sql = "WITH active_jobs AS (\n  SELECT wu.id, wur.id\n  FROM raw.lakeflow_jobs AS j\n  INNER JOIN ledger.work_unit AS wu ON wu.external_id = j.job_id AND wu.type = 'job'\n  INNER JOIN ledger.work_unit_run AS wur ON wur.work_unit_id = wu.id\n)\nSELECT * FROM active_jobs";
        let issues = run(sql);
        assert_eq!(issues.len(), 1);
        let autofix = issues[0]
            .autofix
            .as_ref()
            .expect("expected ST009 autofix metadata");
        let fixed = apply_edits(sql, &autofix.edits);
        assert!(
            fixed.contains("j.job_id = wu.external_id"),
            "expected first join to be reordered, got: {fixed}"
        );
        assert!(
            fixed.contains("wu.id = wur.work_unit_id"),
            "expected second join to be reordered in same patch, got: {fixed}"
        );
    }

    #[test]
    fn emits_autofix_for_workspace_join_after_inner_chain() {
        let sql = "SELECT wur.id\nFROM ledger.work_unit_run AS wur\nINNER JOIN ledger.work_unit AS wu ON wur.work_unit_id = wu.id AND wu.type = 'job'\nINNER JOIN ledger.workspace AS ws ON ws.id = wu.workspace_id";
        let issues = run(sql);
        assert_eq!(issues.len(), 1);
        let autofix = issues[0]
            .autofix
            .as_ref()
            .expect("expected ST009 autofix metadata");
        let fixed = apply_edits(sql, &autofix.edits);
        assert!(
            fixed.contains("wu.workspace_id = ws.id"),
            "expected workspace join predicate reorder, got: {fixed}"
        );
    }

    #[test]
    fn emits_autofix_for_workspace_join_inside_cte_chain() {
        let sql = "WITH job_run_costs AS (\n    SELECT\n        wur.id AS work_unit_run_id,\n        wu.workspace_id\n    FROM ledger.work_unit_run AS wur\n    INNER\n    JOIN ledger.work_unit AS wu ON wur.work_unit_id = wu.id AND wu.type = 'job'\n    INNER JOIN ledger.workspace AS ws ON ws.id = wu.workspace_id\n)\nSELECT * FROM job_run_costs";
        let issues = run(sql);
        assert_eq!(issues.len(), 1);
        assert!(
            issues[0].autofix.is_some(),
            "expected ST009 autofix metadata for CTE join chain"
        );
        let fixed = apply_edits(
            sql,
            &issues[0]
                .autofix
                .as_ref()
                .expect("expected ST009 autofix metadata")
                .edits,
        );
        assert!(
            fixed.contains("wu.workspace_id = ws.id"),
            "expected workspace join predicate reorder, got: {fixed}"
        );
    }

    #[test]
    fn autofix_handles_insert_select_with_on_conflict_join_chain() {
        let sql = "INSERT INTO metrics.page_performance_summary (\n    route,\n    period_start,\n    period_end,\n    nav_type,\n    mark\n)\nSELECT\n    o.route,\n    p.period_start,\n    p.period_end,\n    o.nav_type,\n    o.mark\nFROM overall AS o\nCROSS JOIN params AS p\nLEFT JOIN device_breakdown AS d\n    ON d.route = o.route AND d.nav_type = o.nav_type AND d.mark = o.mark\nLEFT JOIN network_breakdown AS n\n    ON n.route = o.route AND n.nav_type = o.nav_type AND n.mark = o.mark\nLEFT JOIN version_breakdown AS v\n    ON v.route = o.route AND v.nav_type = o.nav_type AND v.mark = o.mark\nON CONFLICT (route, period_start, nav_type, mark) DO UPDATE SET\n    period_end = excluded.period_end;\n";
        let issues = run(sql);
        assert_eq!(issues.len(), 1);
        let autofix = issues[0]
            .autofix
            .as_ref()
            .expect("expected ST009 autofix metadata");
        let fixed = apply_edits(sql, &autofix.edits);
        assert!(
            fixed.contains("ON o.route = d.route AND o.nav_type = d.nav_type AND o.mark = d.mark"),
            "expected first join reordered, got: {fixed}"
        );
        assert!(
            fixed.contains("ON o.route = n.route AND o.nav_type = n.nav_type AND o.mark = n.mark"),
            "expected second join reordered, got: {fixed}"
        );
        assert!(
            fixed.contains("ON o.route = v.route AND o.nav_type = v.nav_type AND o.mark = v.mark"),
            "expected third join reordered, got: {fixed}"
        );
        assert!(
            fixed.contains("ON CONFLICT (route, period_start, nav_type, mark) DO UPDATE SET"),
            "expected ON CONFLICT clause preserved, got: {fixed}"
        );
    }
}