|
| 1 | +//! SQBRSQL045: the same JSON payload column parsed more than once in one SELECT scope. |
| 2 | +
|
| 3 | +use std::borrow::Cow; |
| 4 | +use std::collections::HashMap; |
| 5 | + |
| 6 | +use polyglot_sql::expressions::{Column, Identifier}; |
| 7 | +use polyglot_sql::scope::walk_in_scope; |
| 8 | +use polyglot_sql::tokens::Token; |
| 9 | +use polyglot_sql::{DialectType, Expression, ExpressionWalk}; |
| 10 | + |
| 11 | +use crate::sql_lint::models::LintDiagnostic; |
| 12 | +use crate::sql_quality::constants::REPEATED_JSON_PARSE; |
| 13 | +use crate::sql_quality::models::QualityRequest; |
| 14 | +use crate::sql_quality::syntax::{is_trivia, lower}; |
| 15 | + |
| 16 | +/// Significant tokens searched backwards from the column for the function name. |
| 17 | +const MAX_FUNCTION_NAME_DISTANCE: usize = 32; |
| 18 | +const PARSE_ONCE_FIX_REFUSAL: &str = |
| 19 | + "Parsing the payload once requires naming a column in the CTE that reads it"; |
| 20 | + |
| 21 | +/// An identifier normalised the way the dialect resolves it. |
| 22 | +type IdentifierKey = String; |
| 23 | + |
| 24 | +/// One JSON parse call whose argument resolves to a plain column. |
| 25 | +struct ParseCall<'a> { |
| 26 | + function: &'static str, |
| 27 | + column: &'a Column, |
| 28 | + column_start: usize, |
| 29 | +} |
| 30 | + |
| 31 | +pub(crate) fn diagnostics(request: &QualityRequest<'_>) -> Vec<LintDiagnostic> { |
| 32 | + let functions: &[&'static str] = parse_functions(request.dialect); |
| 33 | + if functions.is_empty() { |
| 34 | + return Vec::new(); |
| 35 | + } |
| 36 | + let mut found: Vec<LintDiagnostic> = Vec::new(); |
| 37 | + for statement in request.statements { |
| 38 | + for node in statement.dfs() { |
| 39 | + if matches!(node, Expression::Select(_)) { |
| 40 | + found.extend(scope_diagnostics( |
| 41 | + request.tokens, |
| 42 | + node, |
| 43 | + functions, |
| 44 | + request.dialect, |
| 45 | + )); |
| 46 | + } |
| 47 | + } |
| 48 | + } |
| 49 | + found |
| 50 | +} |
| 51 | + |
| 52 | +/// JSON parse functions that take one string argument, by dialect, in upper case. |
| 53 | +fn parse_functions(dialect: DialectType) -> &'static [&'static str] { |
| 54 | + match dialect { |
| 55 | + DialectType::Snowflake | DialectType::Databricks => &["PARSE_JSON", "TRY_PARSE_JSON"], |
| 56 | + DialectType::BigQuery => &["PARSE_JSON", "SAFE.PARSE_JSON"], |
| 57 | + DialectType::DuckDB => &["JSON"], |
| 58 | + _ => &[], |
| 59 | + } |
| 60 | +} |
| 61 | + |
| 62 | +fn scope_diagnostics( |
| 63 | + tokens: &[Token], |
| 64 | + select: &Expression, |
| 65 | + functions: &[&'static str], |
| 66 | + dialect: DialectType, |
| 67 | +) -> Vec<LintDiagnostic> { |
| 68 | + let quote: char = identifier_quote(dialect); |
| 69 | + let mut calls: Vec<ParseCall<'_>> = walk_in_scope(select, false) |
| 70 | + .filter_map(|node| parse_call(node, functions)) |
| 71 | + .collect(); |
| 72 | + calls.sort_by_key(|call| call.column_start); |
| 73 | + let mut groups: HashMap< |
| 74 | + (&'static str, Option<IdentifierKey>, IdentifierKey), |
| 75 | + Vec<&ParseCall<'_>>, |
| 76 | + > = HashMap::new(); |
| 77 | + for call in &calls { |
| 78 | + let qualifier: Option<IdentifierKey> = call |
| 79 | + .column |
| 80 | + .table |
| 81 | + .as_ref() |
| 82 | + .map(|table| identifier_key(table, dialect)); |
| 83 | + groups |
| 84 | + .entry(( |
| 85 | + call.function, |
| 86 | + qualifier, |
| 87 | + identifier_key(&call.column.name, dialect), |
| 88 | + )) |
| 89 | + .or_default() |
| 90 | + .push(call); |
| 91 | + } |
| 92 | + let mut found: Vec<LintDiagnostic> = Vec::new(); |
| 93 | + for group in groups.values().filter(|group| group.len() > 1) { |
| 94 | + let second: &ParseCall<'_> = group[1]; |
| 95 | + let (start, end) = function_span(tokens, second); |
| 96 | + found.push(LintDiagnostic { |
| 97 | + code: REPEATED_JSON_PARSE.code, |
| 98 | + message: REPEATED_JSON_PARSE.message, |
| 99 | + remediation: Cow::Owned(remediation(second, group.len(), quote)), |
| 100 | + start, |
| 101 | + end, |
| 102 | + fix: None, |
| 103 | + fix_unavailable_reason: Some(PARSE_ONCE_FIX_REFUSAL), |
| 104 | + }); |
| 105 | + } |
| 106 | + found |
| 107 | +} |
| 108 | + |
| 109 | +/// Normalises a name the way the dialect resolves it (Snowflake folds unquoted names upward). |
| 110 | +fn identifier_key(identifier: &Identifier, dialect: DialectType) -> IdentifierKey { |
| 111 | + match dialect { |
| 112 | + DialectType::Snowflake if identifier.quoted => identifier.name.clone(), |
| 113 | + DialectType::Snowflake => identifier.name.to_uppercase(), |
| 114 | + _ => lower(&identifier.name), |
| 115 | + } |
| 116 | +} |
| 117 | + |
| 118 | +fn parse_call<'a>(node: &'a Expression, functions: &[&'static str]) -> Option<ParseCall<'a>> { |
| 119 | + let (name, argument): (&str, &Expression) = match node { |
| 120 | + Expression::ParseJson(function) => ("PARSE_JSON", &function.this), |
| 121 | + Expression::Function(function) if function.args.len() == 1 => { |
| 122 | + (function.name.as_str(), &function.args[0]) |
| 123 | + } |
| 124 | + _ => return None, |
| 125 | + }; |
| 126 | + let function: &'static str = functions |
| 127 | + .iter() |
| 128 | + .copied() |
| 129 | + .find(|candidate| candidate.eq_ignore_ascii_case(name))?; |
| 130 | + let column: &Column = unwrap_column(argument)?; |
| 131 | + let column_start: usize = column.span.or(column.name.span)?.start; |
| 132 | + Some(ParseCall { |
| 133 | + function, |
| 134 | + column, |
| 135 | + column_start, |
| 136 | + }) |
| 137 | +} |
| 138 | + |
| 139 | +/// The column under wrappers that keep the parsed value tied to that column. |
| 140 | +fn unwrap_column(expression: &Expression) -> Option<&Column> { |
| 141 | + let mut current: &Expression = expression; |
| 142 | + loop { |
| 143 | + current = match current { |
| 144 | + Expression::Column(column) => return Some(column), |
| 145 | + Expression::Paren(paren) => &paren.this, |
| 146 | + Expression::Lower(function) | Expression::Upper(function) => &function.this, |
| 147 | + Expression::Trim(trim) if trim.characters.is_none() => &trim.this, |
| 148 | + Expression::Cast(cast) | Expression::TryCast(cast) | Expression::SafeCast(cast) => { |
| 149 | + &cast.this |
| 150 | + } |
| 151 | + Expression::Coalesce(coalesce) if coalesce.expressions.len() == 1 => { |
| 152 | + &coalesce.expressions[0] |
| 153 | + } |
| 154 | + _ => return None, |
| 155 | + }; |
| 156 | + } |
| 157 | +} |
| 158 | + |
| 159 | +/// Span of the function-name token that opens `call`, or of its column when not found. |
| 160 | +fn function_span(tokens: &[Token], call: &ParseCall<'_>) -> (usize, usize) { |
| 161 | + let bare: &str = call.function.rsplit('.').next().unwrap_or(call.function); |
| 162 | + let before: usize = tokens.partition_point(|token| token.span.start < call.column_start); |
| 163 | + tokens[..before] |
| 164 | + .iter() |
| 165 | + .rev() |
| 166 | + .filter(|token| !is_trivia(token)) |
| 167 | + .take(MAX_FUNCTION_NAME_DISTANCE) |
| 168 | + .find(|token| token.text.eq_ignore_ascii_case(bare)) |
| 169 | + .map_or((call.column_start, call.column_start), |token| { |
| 170 | + (token.span.start, token.span.end) |
| 171 | + }) |
| 172 | +} |
| 173 | + |
| 174 | +fn remediation(call: &ParseCall<'_>, count: usize, quote: char) -> String { |
| 175 | + let name: String = written(&call.column.name, quote); |
| 176 | + let column: String = call.column.table.as_ref().map_or_else( |
| 177 | + || name.clone(), |
| 178 | + |table| format!("{}.{name}", written(table, quote)), |
| 179 | + ); |
| 180 | + let function: &str = call.function; |
| 181 | + format!( |
| 182 | + "{function}({column}) is parsed {count} times in one SELECT. Parse it once in the CTE that reads it, for example `{function}({name}) AS payload`, and read every field from that column in a later step." |
| 183 | + ) |
| 184 | +} |
| 185 | + |
| 186 | +/// The identifier as authored, re-quoted with the dialect's identifier quote when it was quoted. |
| 187 | +fn written(identifier: &Identifier, quote: char) -> String { |
| 188 | + if identifier.quoted { |
| 189 | + let escaped: String = identifier.name.replace(quote, &format!("{quote}{quote}")); |
| 190 | + format!("{quote}{escaped}{quote}") |
| 191 | + } else { |
| 192 | + identifier.name.clone() |
| 193 | + } |
| 194 | +} |
| 195 | + |
| 196 | +fn identifier_quote(dialect: DialectType) -> char { |
| 197 | + match dialect { |
| 198 | + DialectType::BigQuery | DialectType::Databricks => '`', |
| 199 | + _ => '"', |
| 200 | + } |
| 201 | +} |
0 commit comments