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, GroupByExpr, Ident,
7 InTarget, JoinConstraint, JoinOperator, MacroDefinition, Query, Select, SelectItem, SetExpr,
8 Statement, 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) || is_implicit_aggregate_group(select) {
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
385pub(crate) fn select_has_group_by(select: &Select) -> bool {
386 match &select.group_by {
387 GroupByExpr::All(_) => true,
388 GroupByExpr::Expressions(exprs, _) => !exprs.is_empty(),
389 }
390}
391
392pub(crate) fn projection_contains_aggregate(projection: &[SelectItem]) -> bool {
393 projection.iter().any(|item| match item {
394 SelectItem::UnnamedExpr(expr)
395 | SelectItem::ExprWithAlias { expr, .. }
396 | SelectItem::ExprWithAliases { expr, .. } => expr_contains_aggregate(expr),
397 SelectItem::Wildcard(_) | SelectItem::QualifiedWildcard(_, _) => false,
398 })
399}
400
401fn is_implicit_aggregate_group(select: &Select) -> bool {
402 !select_has_group_by(select) && projection_contains_aggregate(&select.projection)
403}
404
405fn collect_aggregate_aliases(projection: &[SelectItem]) -> BTreeSet<String> {
406 let mut aliases = BTreeSet::new();
407 for item in projection {
408 match item {
409 SelectItem::ExprWithAlias { expr, alias } if expr_contains_aggregate(expr) => {
410 aliases.insert(alias.value.to_ascii_lowercase());
411 }
412 SelectItem::ExprWithAliases {
413 expr,
414 aliases: item_aliases,
415 } if expr_contains_aggregate(expr) => {
416 for alias in item_aliases {
417 aliases.insert(alias.value.to_ascii_lowercase());
418 }
419 }
420 _ => {}
421 }
422 }
423 aliases
424}
425
426fn expr_references_any_alias(root: &Expr, aliases: &BTreeSet<String>) -> bool {
427 if aliases.is_empty() {
428 return false;
429 }
430 let mut stack = vec![root];
431 while let Some(expr) = stack.pop() {
432 match expr {
433 Expr::Subquery(_) | Expr::Exists { .. } => {}
434 Expr::Identifier(ident) if aliases.contains(&ident.value.to_ascii_lowercase()) => {
435 return true;
436 }
437 other => push_expr_children_rev(other, &mut stack),
438 }
439 }
440 false
441}
442
443fn flatten_or_operands<'a>(root: &'a Expr, out: &mut Vec<&'a Expr>) {
444 let mut stack = vec![root];
445 while let Some(expr) = stack.pop() {
446 let unwrapped = peel_nested(expr);
447 if let Expr::BinaryOp {
448 left,
449 op: BinaryOperator::Or,
450 right,
451 } = unwrapped
452 {
453 stack.push(right);
454 stack.push(left);
455 } else {
456 out.push(unwrapped);
457 }
458 }
459}
460
461fn extract_column_eq_literal(expr: &Expr) -> Option<(Vec<String>, u32)> {
462 let Expr::BinaryOp {
463 left,
464 op: BinaryOperator::Eq,
465 right,
466 } = peel_nested(expr)
467 else {
468 return None;
469 };
470 let line = expr_start_line(expr);
471 if let Some(col) = extract_column_key(left)
472 && is_constant_literal(right)
473 {
474 return Some((col, line));
475 }
476 if let Some(col) = extract_column_key(right)
477 && is_constant_literal(left)
478 {
479 return Some((col, line));
480 }
481 None
482}
483
484fn extract_column_key(expr: &Expr) -> Option<Vec<String>> {
485 match peel_nested(expr) {
486 Expr::Identifier(ident) => Some(vec![normalize_ident(ident)]),
487 Expr::CompoundIdentifier(idents) if !idents.is_empty() => {
488 Some(idents.iter().map(normalize_ident).collect())
489 }
490 _ => None,
491 }
492}
493
494fn normalize_ident(ident: &Ident) -> String {
495 if ident.quote_style.is_none() {
496 ident.value.to_ascii_lowercase()
497 } else {
498 ident.value.clone()
499 }
500}
501
502pub(crate) fn is_bare_number_literal(expr: &Expr) -> bool {
503 match peel_nested(expr) {
504 Expr::Value(val) => matches!(val.value, Value::Number(_, _)),
505 Expr::UnaryOp {
506 op: UnaryOperator::Plus | UnaryOperator::Minus,
507 expr: inner,
508 } => matches!(
509 peel_nested(inner),
510 Expr::Value(val) if matches!(val.value, Value::Number(_, _))
511 ),
512 _ => false,
513 }
514}
515
516fn is_constant_literal(expr: &Expr) -> bool {
517 if is_bare_number_literal(expr) {
518 return true;
519 }
520 match peel_nested(expr) {
521 Expr::Value(val) => !matches!(val.value, Value::Null | Value::Placeholder(_)),
522 Expr::TypedString(_) => true,
523 _ => false,
524 }
525}
526
527pub(crate) fn expr_contains_aggregate(root: &Expr) -> bool {
528 let mut stack = vec![root];
529 while let Some(expr) = stack.pop() {
530 match expr {
531 Expr::Subquery(_) | Expr::Exists { .. } => {}
532 Expr::Function(func) => {
533 if is_aggregate_call(func) {
534 return true;
535 }
536 push_expr_children_rev(expr, &mut stack);
537 }
538 other => push_expr_children_rev(other, &mut stack),
539 }
540 }
541 false
542}
543
544pub(crate) fn is_aggregate_call(func: &Function) -> bool {
545 if func.over.is_some() {
546 return false;
547 }
548 if func.filter.is_some() || !func.within_group.is_empty() {
549 return true;
550 }
551 if let FunctionArguments::List(list) = &func.args
552 && list.duplicate_treatment == Some(DuplicateTreatment::Distinct)
553 {
554 return true;
555 }
556 let Some(last_ident) = func.name.0.last().and_then(|part| part.as_ident()) else {
557 return false;
558 };
559 let lower = last_ident.value.to_ascii_lowercase();
560 AGGREGATE_FUNCTIONS.binary_search(&lower.as_str()).is_ok()
561}
562
563fn find_having_line(tokens: &[TokenWithSpan], expr_start: Location) -> Option<u32> {
564 if expr_start.line == 0 {
565 return tokens
566 .iter()
567 .find(|t| matches!(&t.token, Token::Word(w) if w.keyword == Keyword::HAVING))
568 .map(|t| t.span.start.line as u32);
569 }
570 let before = tokens
571 .iter()
572 .rposition(|t| t.span.start < expr_start && !matches!(t.token, Token::Whitespace(_)))?;
573 for tok in tokens[..=before].iter().rev() {
574 if matches!(tok.token, Token::Whitespace(_) | Token::LParen) {
575 continue;
576 }
577 if matches!(&tok.token, Token::Word(w) if w.keyword == Keyword::HAVING) {
578 return Some(tok.span.start.line as u32);
579 }
580 break;
581 }
582 None
583}