Skip to content

Commit 20f2974

Browse files
committed
fix(lint): resolve a named window written after a parenthesized query
Databricks keeps a WINDOW clause written after a parenthesized query on the subquery node, but the ranking rules looked a window name up only in the SELECT's own WINDOW clause. SQLCLEAN018 and SQLCLEAN043 were therefore silent for (SELECT ..., ROW_NUMBER() OVER w AS rn FROM orders) WINDOW w AS (ORDER BY ...), with or without a WITH before the parentheses. An OVER name now resolves against the SELECT's own windows, then the enclosing WINDOW clauses, nearest first: those after parentheses and those of outer SELECTs whose FROM holds the query, so a nearer definition of the same name wins, as in Spark. Databricks cases cover both rules, the WITH form, a proven ordering and a name defined at two levels. The key inference for ROW_NUMBER() = 1 dedups still reads only an inline OVER, as before.
1 parent 04dab55 commit 20f2974

2 files changed

Lines changed: 80 additions & 6 deletions

File tree

‎crates/sqlquack-lint/src/quality/_helpers/ranking.rs‎

Lines changed: 40 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,8 @@ use std::collections::{HashMap, HashSet};
66
use crate::tree::main::call_name::call_name;
77
use crate::tree::main::walk_in_scope::walk_in_scope;
88
use sqlquack_syntax::expressions::functions::models::WindowFunction;
9-
use sqlquack_syntax::expressions::queries::models::Over;
109
use sqlquack_syntax::expressions::queries::models::Select;
10+
use sqlquack_syntax::expressions::queries::models::{NamedWindow, Over};
1111
use sqlquack_syntax::tokens::models::Token;
1212
use sqlquack_syntax::{Expression, ExpressionWalk};
1313

@@ -31,6 +31,8 @@ struct RankingWindow<'a> {
3131
function: &'static str,
3232
window: &'a WindowFunction,
3333
select: &'a Select,
34+
/// The WINDOW clauses its OVER can name: the SELECT's own, then those after enclosing parentheses.
35+
windows: Vec<&'a NamedWindow>,
3436
}
3537

3638
pub(crate) fn diagnostics(
@@ -55,7 +57,7 @@ pub(crate) fn diagnostics(
5557
}
5658
let mut found: Vec<LintDiagnostic> = Vec::new();
5759
for ranking in ranking_windows(request.statements) {
58-
let over: Option<&Over> = effective_over(&ranking.window.over, ranking.select);
60+
let over: Option<&Over> = effective_over(&ranking.window.over, &ranking.windows);
5961
let order: Vec<&Expression> = over.map_or_else(Vec::new, |over| {
6062
over.order_by.iter().map(|ordered| &ordered.this).collect()
6163
});
@@ -140,10 +142,15 @@ fn proven(
140142
fn ranking_windows(statements: &[Expression]) -> Vec<RankingWindow<'_>> {
141143
let mut found: Vec<RankingWindow<'_>> = Vec::new();
142144
for statement in statements {
145+
let outer: HashMap<*const Select, Vec<&NamedWindow>> = enclosing_windows(statement);
143146
for node in statement.dfs() {
144147
let Expression::Select(select) = node else {
145148
continue;
146149
};
150+
let mut windows: Vec<&NamedWindow> = select.windows.iter().flatten().collect();
151+
if let Some(enclosing) = outer.get(&std::ptr::from_ref(select.as_ref())) {
152+
windows.extend(enclosing.iter().rev());
153+
}
147154
for local in walk_in_scope(node) {
148155
let Expression::WindowFunction(window) = local else {
149156
continue;
@@ -167,14 +174,43 @@ fn ranking_windows(statements: &[Expression]) -> Vec<RankingWindow<'_>> {
167174
function,
168175
window,
169176
select,
177+
windows: windows.clone(),
170178
});
171179
}
172180
}
173181
}
174182
found
175183
}
176184

177-
fn effective_over<'a>(over: &'a Over, select: &'a Select) -> Option<&'a Over> {
185+
/// Each SELECT's enclosing WINDOW clauses, from parentheses and outer SELECTs, outermost first.
186+
fn enclosing_windows(statement: &Expression) -> HashMap<*const Select, Vec<&NamedWindow>> {
187+
let mut found: HashMap<*const Select, Vec<&NamedWindow>> = HashMap::new();
188+
for node in statement.dfs() {
189+
let (windows, inside): (&[NamedWindow], Box<dyn Iterator<Item = &Expression>>) = match node
190+
{
191+
Expression::Subquery(subquery) => match &subquery.windows {
192+
Some(windows) => (windows, Box::new(subquery.this.dfs())),
193+
None => continue,
194+
},
195+
Expression::Select(select) => match &select.windows {
196+
Some(windows) => (windows, Box::new(node.dfs().skip(1))),
197+
None => continue,
198+
},
199+
_ => continue,
200+
};
201+
for inner in inside {
202+
if let Expression::Select(select) = inner {
203+
found
204+
.entry(std::ptr::from_ref(select.as_ref()))
205+
.or_default()
206+
.extend(windows);
207+
}
208+
}
209+
}
210+
found
211+
}
212+
213+
fn effective_over<'a>(over: &'a Over, windows: &[&'a NamedWindow]) -> Option<&'a Over> {
178214
let mut current: &Over = over;
179215
let mut seen: HashSet<String> = HashSet::new();
180216
loop {
@@ -185,10 +221,8 @@ fn effective_over<'a>(over: &'a Over, select: &'a Select) -> Option<&'a Over> {
185221
if !seen.insert(name.clone()) {
186222
return None;
187223
}
188-
current = &select
189-
.windows
224+
current = &windows
190225
.iter()
191-
.flatten()
192226
.find(|window| lower(&window.name.name) == name)?
193227
.spec;
194228
}

‎crates/sqlquack-lint/src/quality/tests/test_quality_rules.rs‎

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -567,6 +567,46 @@ fn given_a_query_or_cte_body_in_parentheses_when_linting_then_its_ctes_are_check
567567
expected_anchors: &[],
568568
expected_fixed_sql: None,
569569
},
570+
QualityRuleTestCase {
571+
description: "a ranking sort above the cap in a WINDOW after the parentheses",
572+
sql: "(SELECT o.order_id, ROW_NUMBER() OVER w AS rn FROM orders AS o) WINDOW w AS (ORDER BY o.a, o.b, o.c)",
573+
rule: "SQLCLEAN043",
574+
relation_keys: r#"{}"#,
575+
expected_anchors: &["ROW_NUMBER"],
576+
expected_fixed_sql: None,
577+
},
578+
QualityRuleTestCase {
579+
description: "a ranking sort above the cap in a WINDOW after parentheses with a WITH before them",
580+
sql: "WITH c AS (SELECT 1 AS x) (SELECT o.order_id, ROW_NUMBER() OVER w AS rn FROM orders AS o) WINDOW w AS (ORDER BY o.a, o.b, o.c)",
581+
rule: "SQLCLEAN043",
582+
relation_keys: r#"{}"#,
583+
expected_anchors: &["ROW_NUMBER"],
584+
expected_fixed_sql: None,
585+
},
586+
QualityRuleTestCase {
587+
description: "an ordering without a key in a WINDOW after the parentheses is unproven",
588+
sql: "(SELECT o.order_id, ROW_NUMBER() OVER w AS rn FROM orders AS o) WINDOW w AS (ORDER BY o.ordered_at)",
589+
rule: "SQLCLEAN018",
590+
relation_keys: r#"{"orders": [["order_id"]]}"#,
591+
expected_anchors: &["ROW_NUMBER"],
592+
expected_fixed_sql: None,
593+
},
594+
QualityRuleTestCase {
595+
description: "a nested SELECT's window resolves to the nearer WINDOW, not the one after the parentheses",
596+
sql: "(SELECT s.rn FROM (SELECT o.order_id, ROW_NUMBER() OVER w AS rn FROM orders AS o) AS s WINDOW w AS (ORDER BY o.a, o.b, o.c)) WINDOW w AS (ORDER BY o.order_id)",
597+
rule: "SQLCLEAN043",
598+
relation_keys: r#"{}"#,
599+
expected_anchors: &["ROW_NUMBER"],
600+
expected_fixed_sql: None,
601+
},
602+
QualityRuleTestCase {
603+
description: "an ordering by the key in a WINDOW after the parentheses is proven",
604+
sql: "(SELECT o.order_id, ROW_NUMBER() OVER w AS rn FROM orders AS o) WINDOW w AS (ORDER BY o.order_id)",
605+
rule: "SQLCLEAN018",
606+
relation_keys: r#"{"orders": [["order_id"]]}"#,
607+
expected_anchors: &[],
608+
expected_fixed_sql: None,
609+
},
570610
];
571611
for test_case in &test_cases {
572612
let diagnostics: Vec<Value> =

0 commit comments

Comments
 (0)