use super::bindings::{self, variable_key, Variables};
use super::literal::{normalize_format, string_expression};
use super::routine::{bodies, RoutineBody};
use super::*;
pub(super) fn extract(sql: &str) -> Vec<DynamicSql> {
bodies(sql).iter().flat_map(extract_body).collect()
}
fn extract_body(body: &RoutineBody) -> Vec<DynamicSql> {
let all = tokenize(&body.sql);
let mut variables = Variables::new();
let mut blocks = bindings::Blocks::default();
let mut result = Vec::new();
let mut scope = execution::Scope::default();
for (ordinal, statement) in statements(&all).into_iter().enumerate() {
let code = significant(statement);
let definite = scope.advance(&code);
let executed = definite && body.executed;
if code.is_empty() {
continue;
}
blocks.enter(&code, &mut variables);
if let Some(at) = code.iter().position(|token| word(token, "EXECUTE")) {
let origin = body_origin(body, code[at]);
if let Some(mut sql) =
executed_expression(&code[at + 1..], statement, &variables, body, origin)
{
sql.executed &= executed;
sql.stored_routine = !body.executed;
sql.trigger_function = body.trigger_function;
sql.source_order = body
.source_order
.iter()
.copied()
.chain(std::iter::once(ordinal))
.collect();
result.push(sql);
}
continue;
}
if let Some(at) = assignment_at(&code) {
if let Some((qualifier, name)) = assignment_name(&code, at) {
let origin = body_origin(body, code[at]);
let mut value =
executed_expression(&code[at + 1..], statement, &variables, body, origin);
if let Some(value) = &mut value {
value.executed &= definite;
}
blocks.assign(qualifier.as_deref(), name, value, &mut variables);
}
}
}
result
}
fn executed_expression(
tokens: &[&TokenWithSpan],
original: &[TokenWithSpan],
variables: &Variables,
body: &RoutineBody,
origin: Origin,
) -> Option<DynamicSql> {
let expression = execution_tokens(tokens);
if expression.len() == 1 {
if let Some(value) = variable_key(expression[0])
.and_then(|name| variables.get(&name))
.and_then(|value| value.as_ref())
{
return Some(value.clone());
}
}
static_expression(expression, original, body, origin)
}
fn execution_tokens<'a>(tokens: &'a [&TokenWithSpan]) -> &'a [&'a TokenWithSpan] {
let end = tokens
.iter()
.position(|token| word(token, "INTO") || word(token, "USING"))
.unwrap_or(tokens.len());
&tokens[..end]
}
fn static_expression(
tokens: &[&TokenWithSpan],
original: &[TokenWithSpan],
body: &RoutineBody,
origin: Origin,
) -> Option<DynamicSql> {
if tokens
.iter()
.any(|token| matches!(token.token, Token::StringConcat | Token::Plus))
{
return None;
}
if let Some(decoded) = string_expression(tokens, Some(&body.sql), original) {
let mut value = DynamicSql::anchored(decoded.sql, origin.line);
value.anchor_offset = origin.offset;
value.source_bytes = decoded
.source_bytes
.iter()
.map(|part| {
body.source_bytes
.get(part.offset)
.copied()
.unwrap_or(origin)
})
.collect();
return Some(value);
}
if let Some(argument_start) = format_argument_start(tokens) {
let comma = tokens
.iter()
.position(|token| matches!(token.token, Token::Comma))
.unwrap_or(tokens.len().saturating_sub(1));
return string_expression(&tokens[argument_start..comma], None, original).map(|decoded| {
let normalized = normalize_format(&decoded.sql);
let mut value = DynamicSql::anchored(normalized.sql, origin.line);
value.anchor_offset = origin.offset;
value.executed = normalized.concrete;
value
});
}
None
}
fn format_argument_start(tokens: &[&TokenWithSpan]) -> Option<usize> {
if tokens.len() >= 3 && word(tokens[0], "FORMAT") && matches!(tokens[1].token, Token::LParen) {
return Some(2);
}
(tokens.len() >= 5
&& word(tokens[0], "pg_catalog")
&& matches!(tokens[1].token, Token::Period)
&& word(tokens[2], "FORMAT")
&& matches!(tokens[3].token, Token::LParen))
.then_some(4)
}
fn assignment_name(
tokens: &[&TokenWithSpan],
assignment: usize,
) -> Option<(Option<String>, String)> {
let prefix = &tokens[..assignment];
let boundary = prefix.iter().rposition(|token| {
matches!(&token.token, Token::Word(word) if word.quote_style.is_none()
&& matches!(word.value.to_ascii_uppercase().as_str(), "DECLARE" | "BEGIN" | "THEN" | "ELSE" | "LOOP"))
});
let target = &prefix[boundary.map_or(0, |index| index + 1)..];
let name = target.first()?;
if matches!(&name.token, Token::Word(word) if word.quote_style.is_none() && is_control_word(&word.value))
{
return None;
}
if let [qualifier, dot, name] = target {
if matches!(dot.token, Token::Period) {
return Some((Some(variable_key(qualifier)?), variable_key(name)?));
}
}
Some((None, variable_key(name)?))
}
fn assignment_at(tokens: &[&TokenWithSpan]) -> Option<usize> {
tokens
.iter()
.position(|token| matches!(token.token, Token::Assignment))
.or_else(|| {
tokens.iter().enumerate().find_map(|(index, token)| {
if !matches!(token.token, Token::Eq) {
return None;
}
assignment_name(tokens, index).map(|_| index)
})
})
}
fn is_control_word(word: &str) -> bool {
matches!(
word.to_ascii_uppercase().as_str(),
"IF" | "ELSIF" | "ELSEIF" | "WHILE" | "WHEN" | "EXIT" | "RETURN" | "BEGIN" | "LOOP"
)
}