1use std::collections::{BTreeMap, BTreeSet};
2
3use codeint_model::language::FlaggedLine;
4use codeint_model::scan::{finalize_flagged, flag_range};
5use sqlparser::ast::{
6 BinaryOperator, DuplicateTreatment, Expr, Function, FunctionArguments, Ident, InTarget,
7 JoinConstraint, JoinOperator, MacroDefinition, Query, Select, SelectItem, SetExpr, Statement,
8 TableFactor, TableWithJoins, UnaryOperator, Value,
9};
10use sqlparser::keywords::Keyword;
11use sqlparser::tokenizer::{Location, Token, TokenWithSpan};
12
13use crate::ParsedSqlStatement;
14use crate::ast_loc::{expr_start_line, expr_start_loc, peel_nested, push_expr_children_rev};
15
16const RULES: &[&str] = &["or-chain-collapses-to-in", "having-without-aggregate"];
17
18const AGGREGATE_FUNCTIONS: &[&str] = &[
19 "any",
20 "any_value",
21 "approx_count_distinct",
22 "approx_quantile",
23 "arg_max",
24 "arg_min",
25 "argmax",
26 "argmin",
27 "array_agg",
28 "avg",
29 "bit_and",
30 "bit_or",
31 "bit_xor",
32 "bitstring_agg",
33 "bool_and",
34 "bool_or",
35 "corr",
36 "count",
37 "count_if",
38 "covar_pop",
39 "covar_samp",
40 "entropy",
41 "every",
42 "favg",
43 "first",
44 "fsum",
45 "group_concat",
46 "grouping",
47 "histogram",
48 "json_agg",
49 "json_arrayagg",
50 "json_group_array",
51 "json_group_object",
52 "json_object_agg",
53 "json_objectagg",
54 "jsonb_agg",
55 "jsonb_object_agg",
56 "kahan_sum",
57 "kurtosis",
58 "last",
59 "list",
60 "mad",
61 "max",
62 "median",
63 "min",
64 "mode",
65 "percentile_cont",
66 "percentile_disc",
67 "product",
68 "quantile",
69 "quantile_cont",
70 "quantile_disc",
71 "range_agg",
72 "range_intersect_agg",
73 "regr_avgx",
74 "regr_avgy",
75 "regr_count",
76 "regr_intercept",
77 "regr_r2",
78 "regr_slope",
79 "regr_sxx",
80 "regr_sxy",
81 "regr_syy",
82 "reservoir_quantile",
83 "skewness",
84 "some",
85 "std",
86 "stddev",
87 "stddev_pop",
88 "stddev_samp",
89 "string_agg",
90 "sum",
91 "sum_if",
92 "total",
93 "var_pop",
94 "var_samp",
95 "variance",
96 "xmlagg",
97];
98
99pub fn flagged_line_rules() -> impl Iterator<Item = &'static str> {
100 RULES.iter().copied()
101}
102
103pub(crate) fn evaluate(
104 parsed: &[ParsedSqlStatement],
105 code_lines: &BTreeSet<u32>,
106) -> Vec<FlaggedLine> {
107 let mut hits = BTreeSet::new();
108 for stmt in parsed {
109 let mut checker = StatementChecker {
110 tokens: &stmt.tokens,
111 stmt_start_line: stmt.start_line,
112 code_lines,
113 hits: &mut hits,
114 };
115 checker.visit_statement(&stmt.statement);
116 }
117 finalize_flagged(hits)
118}
119
120struct StatementChecker<'a> {
121 tokens: &'a [TokenWithSpan],
122 stmt_start_line: u32,
123 code_lines: &'a BTreeSet<u32>,
124 hits: &'a mut BTreeSet<(u32, &'static str)>,
125}
126
127impl StatementChecker<'_> {
128 fn flag(&mut self, line: u32, rule: &'static str) {
129 let target = if line > 0 { line } else { self.stmt_start_line };
130 flag_range(target, target, rule, self.code_lines, self.hits);
131 }
132
133 fn visit_statement(&mut self, stmt: &Statement) {
134 match stmt {
135 Statement::Query(query) => self.visit_query(query),
136 Statement::Explain { statement, .. } => self.visit_statement(statement),
137 Statement::Insert(_)
138 | Statement::Update(_)
139 | Statement::Delete(_)
140 | Statement::Merge(_) => {
141 self.visit_dml_statement(stmt);
142 }
143 _ => self.visit_ddl_statement(stmt),
144 }
145 }
146
147 fn visit_dml_statement(&mut self, stmt: &Statement) {
148 match stmt {
149 Statement::Insert(insert) => self.visit_opt_query(insert.source.as_deref()),
150 Statement::Update(update) => self.visit_update(update),
151 Statement::Delete(delete) => self.visit_opt_expr(delete.selection.as_ref()),
152 Statement::Merge(merge) => self.visit_merge(merge),
153 _ => {}
154 }
155 }
156
157 fn visit_ddl_statement(&mut self, stmt: &Statement) {
158 match stmt {
159 Statement::CreateView(view) => self.visit_query(&view.query),
160 Statement::CreateTable(table) => self.visit_opt_query(table.query.as_deref()),
161 Statement::CreateIndex(index) => self.visit_opt_expr(index.predicate.as_ref()),
162 Statement::CreateMacro { definition, .. } => self.visit_macro_def(definition),
163 _ => {}
164 }
165 }
166
167 fn visit_opt_query(&mut self, query: Option<&Query>) {
168 if let Some(q) = query {
169 self.visit_query(q);
170 }
171 }
172
173 fn visit_opt_expr(&mut self, expr: Option<&Expr>) {
174 if let Some(e) = expr {
175 self.visit_expr(e);
176 }
177 }
178
179 fn visit_update(&mut self, update: &sqlparser::ast::Update) {
180 self.visit_table_with_joins(&update.table);
181 for assign in &update.assignments {
182 self.visit_expr(&assign.value);
183 }
184 self.visit_opt_expr(update.selection.as_ref());
185 }
186
187 fn visit_merge(&mut self, merge: &sqlparser::ast::Merge) {
188 self.visit_expr(&merge.on);
189 for clause in &merge.clauses {
190 self.visit_opt_expr(clause.predicate.as_ref());
191 }
192 }
193
194 fn visit_macro_def(&mut self, definition: &MacroDefinition) {
195 match definition {
196 MacroDefinition::Expr(expr) => self.visit_expr(expr),
197 MacroDefinition::Table(query) => self.visit_query(query),
198 }
199 }
200
201 fn visit_query(&mut self, query: &Query) {
202 if let Some(with) = &query.with {
203 for cte in &with.cte_tables {
204 self.visit_query(&cte.query);
205 }
206 }
207 self.visit_set_expr(&query.body);
208 }
209
210 fn visit_set_expr(&mut self, set_expr: &SetExpr) {
211 let mut stack = vec![set_expr];
212 while let Some(current) = stack.pop() {
213 match current {
214 SetExpr::Select(select) => self.visit_select(select),
215 SetExpr::Query(query) => self.visit_query(query),
216 SetExpr::SetOperation { left, right, .. } => {
217 stack.push(right);
218 stack.push(left);
219 }
220 SetExpr::Insert(stmt)
221 | SetExpr::Update(stmt)
222 | SetExpr::Delete(stmt)
223 | SetExpr::Merge(stmt) => self.visit_statement(stmt),
224 _ => {}
225 }
226 }
227 }
228
229 fn visit_select(&mut self, select: &Select) {
230 for item in &select.projection {
231 self.visit_select_item(item);
232 }
233 for table in &select.from {
234 self.visit_table_with_joins(table);
235 }
236 if let Some(prewhere) = &select.prewhere {
237 self.visit_expr(prewhere);
238 }
239 if let Some(selection) = &select.selection {
240 self.visit_expr(selection);
241 }
242 if let Some(having) = &select.having {
243 self.check_having_without_aggregate(select, having);
244 self.visit_expr(having);
245 }
246 if let Some(qualify) = &select.qualify {
247 self.visit_expr(qualify);
248 }
249 }
250
251 fn visit_select_item(&mut self, item: &SelectItem) {
252 match item {
253 SelectItem::UnnamedExpr(expr)
254 | SelectItem::ExprWithAlias { expr, .. }
255 | SelectItem::ExprWithAliases { expr, .. } => self.visit_expr(expr),
256 SelectItem::QualifiedWildcard(_, _) | SelectItem::Wildcard(_) => {}
257 }
258 }
259
260 fn visit_table_with_joins(&mut self, table: &TableWithJoins) {
261 self.visit_table_factor(&table.relation);
262 for join in &table.joins {
263 self.visit_table_factor(&join.relation);
264 self.visit_join_operator(&join.join_operator);
265 }
266 }
267
268 fn visit_table_factor(&mut self, factor: &TableFactor) {
269 match factor {
270 TableFactor::Derived { subquery, .. } => self.visit_query(subquery),
271 TableFactor::NestedJoin {
272 table_with_joins, ..
273 } => self.visit_table_with_joins(table_with_joins),
274 _ => {}
275 }
276 }
277
278 fn visit_join_operator(&mut self, op: &JoinOperator) {
279 match op {
280 JoinOperator::Join(c)
281 | JoinOperator::Inner(c)
282 | JoinOperator::Left(c)
283 | JoinOperator::LeftOuter(c)
284 | JoinOperator::Right(c)
285 | JoinOperator::RightOuter(c)
286 | JoinOperator::FullOuter(c)
287 | JoinOperator::CrossJoin(c)
288 | JoinOperator::Semi(c)
289 | JoinOperator::LeftSemi(c)
290 | JoinOperator::RightSemi(c)
291 | JoinOperator::Anti(c)
292 | JoinOperator::LeftAnti(c)
293 | JoinOperator::RightAnti(c) => self.visit_join_constraint(c),
294 JoinOperator::AsOf {
295 match_condition,
296 constraint,
297 } => {
298 self.visit_expr(match_condition);
299 self.visit_join_constraint(constraint);
300 }
301 _ => {}
302 }
303 }
304
305 fn visit_join_constraint(&mut self, constraint: &JoinConstraint) {
306 if let JoinConstraint::On(expr) = constraint {
307 self.visit_expr(expr);
308 }
309 }
310
311 fn check_having_without_aggregate(&mut self, select: &Select, having: &Expr) {
312 if expr_contains_aggregate(having) {
313 return;
314 }
315 let aggregate_aliases = collect_aggregate_aliases(&select.projection);
316 if expr_references_any_alias(having, &aggregate_aliases) {
317 return;
318 }
319 let start = expr_start_loc(having);
320 let line = find_having_line(self.tokens, start).unwrap_or(start.line as u32);
321 self.flag(line, "having-without-aggregate");
322 }
323
324 fn visit_expr(&mut self, root: &Expr) {
325 let mut stack = vec![root];
326 while let Some(expr) = stack.pop() {
327 match expr {
328 Expr::BinaryOp {
329 op: BinaryOperator::Or,
330 ..
331 } => self.inspect_or_chain(expr, &mut stack),
332 Expr::Subquery(query)
333 | Expr::Exists {
334 subquery: query, ..
335 } => self.visit_query(query),
336 Expr::In {
337 target: InTarget::Subquery(query),
338 ..
339 } => {
340 self.visit_query(query);
341 push_expr_children_rev(expr, &mut stack);
342 }
343 Expr::Function(func) => {
344 if let FunctionArguments::Subquery(query) = &func.args {
345 self.visit_query(query);
346 }
347 push_expr_children_rev(expr, &mut stack);
348 }
349 _ => push_expr_children_rev(expr, &mut stack),
350 }
351 }
352 }
353
354 fn inspect_or_chain<'a>(&mut self, root: &'a Expr, stack: &mut Vec<&'a Expr>) {
355 let mut operands = Vec::new();
356 flatten_or_operands(root, &mut operands);
357
358 let mut counts: BTreeMap<Vec<String>, (usize, u32)> = BTreeMap::new();
359 let mut deferred = Vec::new();
360 for &operand in &operands {
361 if let Some((col_key, line)) = extract_column_eq_literal(operand) {
362 counts
363 .entry(col_key)
364 .and_modify(|(count, first_line)| {
365 *count += 1;
366 if line > 0 && (*first_line == 0 || line < *first_line) {
367 *first_line = line;
368 }
369 })
370 .or_insert((1, line));
371 } else {
372 deferred.push(operand);
373 }
374 }
375 stack.extend(deferred.into_iter().rev());
376
377 for (count, first_line) in counts.into_values() {
378 if count >= 3 {
379 self.flag(first_line, "or-chain-collapses-to-in");
380 }
381 }
382 }
383}
384
385fn collect_aggregate_aliases(projection: &[SelectItem]) -> BTreeSet<String> {
386 let mut aliases = BTreeSet::new();
387 for item in projection {
388 match item {
389 SelectItem::ExprWithAlias { expr, alias } if expr_contains_aggregate(expr) => {
390 aliases.insert(alias.value.to_ascii_lowercase());
391 }
392 SelectItem::ExprWithAliases {
393 expr,
394 aliases: item_aliases,
395 } if expr_contains_aggregate(expr) => {
396 for alias in item_aliases {
397 aliases.insert(alias.value.to_ascii_lowercase());
398 }
399 }
400 _ => {}
401 }
402 }
403 aliases
404}
405
406fn expr_references_any_alias(root: &Expr, aliases: &BTreeSet<String>) -> bool {
407 if aliases.is_empty() {
408 return false;
409 }
410 let mut stack = vec![root];
411 while let Some(expr) = stack.pop() {
412 match expr {
413 Expr::Subquery(_) | Expr::Exists { .. } => {}
414 Expr::Identifier(ident) if aliases.contains(&ident.value.to_ascii_lowercase()) => {
415 return true;
416 }
417 other => push_expr_children_rev(other, &mut stack),
418 }
419 }
420 false
421}
422
423fn flatten_or_operands<'a>(root: &'a Expr, out: &mut Vec<&'a Expr>) {
424 let mut stack = vec![root];
425 while let Some(expr) = stack.pop() {
426 let unwrapped = peel_nested(expr);
427 if let Expr::BinaryOp {
428 left,
429 op: BinaryOperator::Or,
430 right,
431 } = unwrapped
432 {
433 stack.push(right);
434 stack.push(left);
435 } else {
436 out.push(unwrapped);
437 }
438 }
439}
440
441fn extract_column_eq_literal(expr: &Expr) -> Option<(Vec<String>, u32)> {
442 let Expr::BinaryOp {
443 left,
444 op: BinaryOperator::Eq,
445 right,
446 } = peel_nested(expr)
447 else {
448 return None;
449 };
450 let line = expr_start_line(expr);
451 if let Some(col) = extract_column_key(left)
452 && is_constant_literal(right)
453 {
454 return Some((col, line));
455 }
456 if let Some(col) = extract_column_key(right)
457 && is_constant_literal(left)
458 {
459 return Some((col, line));
460 }
461 None
462}
463
464fn extract_column_key(expr: &Expr) -> Option<Vec<String>> {
465 match peel_nested(expr) {
466 Expr::Identifier(ident) => Some(vec![normalize_ident(ident)]),
467 Expr::CompoundIdentifier(idents) if !idents.is_empty() => {
468 Some(idents.iter().map(normalize_ident).collect())
469 }
470 _ => None,
471 }
472}
473
474fn normalize_ident(ident: &Ident) -> String {
475 if ident.quote_style.is_none() {
476 ident.value.to_ascii_lowercase()
477 } else {
478 ident.value.clone()
479 }
480}
481
482pub(crate) fn is_bare_number_literal(expr: &Expr) -> bool {
483 match peel_nested(expr) {
484 Expr::Value(val) => matches!(val.value, Value::Number(_, _)),
485 Expr::UnaryOp {
486 op: UnaryOperator::Plus | UnaryOperator::Minus,
487 expr: inner,
488 } => matches!(
489 peel_nested(inner),
490 Expr::Value(val) if matches!(val.value, Value::Number(_, _))
491 ),
492 _ => false,
493 }
494}
495
496fn is_constant_literal(expr: &Expr) -> bool {
497 if is_bare_number_literal(expr) {
498 return true;
499 }
500 match peel_nested(expr) {
501 Expr::Value(val) => !matches!(val.value, Value::Null | Value::Placeholder(_)),
502 Expr::TypedString(_) => true,
503 _ => false,
504 }
505}
506
507pub(crate) fn expr_contains_aggregate(root: &Expr) -> bool {
508 let mut stack = vec![root];
509 while let Some(expr) = stack.pop() {
510 match expr {
511 Expr::Subquery(_) | Expr::Exists { .. } => {}
512 Expr::Function(func) => {
513 if is_aggregate_call(func) {
514 return true;
515 }
516 push_expr_children_rev(expr, &mut stack);
517 }
518 other => push_expr_children_rev(other, &mut stack),
519 }
520 }
521 false
522}
523
524pub(crate) fn is_aggregate_call(func: &Function) -> bool {
525 if func.over.is_some() {
526 return false;
527 }
528 if func.filter.is_some() || !func.within_group.is_empty() {
529 return true;
530 }
531 if let FunctionArguments::List(list) = &func.args
532 && list.duplicate_treatment == Some(DuplicateTreatment::Distinct)
533 {
534 return true;
535 }
536 let Some(last_ident) = func.name.0.last().and_then(|part| part.as_ident()) else {
537 return false;
538 };
539 let lower = last_ident.value.to_ascii_lowercase();
540 AGGREGATE_FUNCTIONS.binary_search(&lower.as_str()).is_ok()
541}
542
543fn find_having_line(tokens: &[TokenWithSpan], expr_start: Location) -> Option<u32> {
544 if expr_start.line == 0 {
545 return tokens
546 .iter()
547 .find(|t| matches!(&t.token, Token::Word(w) if w.keyword == Keyword::HAVING))
548 .map(|t| t.span.start.line as u32);
549 }
550 let before = tokens
551 .iter()
552 .rposition(|t| t.span.start < expr_start && !matches!(t.token, Token::Whitespace(_)))?;
553 for tok in tokens[..=before].iter().rev() {
554 if matches!(tok.token, Token::Whitespace(_) | Token::LParen) {
555 continue;
556 }
557 if matches!(&tok.token, Token::Word(w) if w.keyword == Keyword::HAVING) {
558 return Some(tok.span.start.line as u32);
559 }
560 break;
561 }
562 None
563}