use crate::erased_visit::VisitErased;
use std::ops::ControlFlow;
use sqlparser::ast::{
Expr, Function, FunctionArg, FunctionArguments, ObjectName, ObjectNamePart, TableFactor, Value,
Visit, Visitor,
};
use super::SqlIsolation;
use crate::idents::{function_arg_expr, unwrap_expr};
pub(in super::super) fn possible_default_isolation(node: &impl Visit) -> Option<SqlIsolation> {
let mut visitor = PossibleDefaultIsolation(None);
let _ = node.visit_erased(&mut visitor);
visitor.0
}
pub(super) enum IsolationSetting<'a> {
Default(&'a [FunctionArg]),
Unknown,
}
pub(super) fn isolation_setting(function: &Function) -> Option<IsolationSetting<'_>> {
let FunctionArguments::List(list) = &function.args else {
return None;
};
classify_call(&function.name, &list.args)
}
fn classify_call<'a>(name: &ObjectName, args: &'a [FunctionArg]) -> Option<IsolationSetting<'a>> {
let qualified = match name.0.as_slice() {
[schema, name] if identifies(schema, "pg_catalog") && identifies(name, "set_config") => {
true
}
[_, schema, name] if identifies(schema, "pg_catalog") && identifies(name, "set_config") => {
false
}
[name] if identifies(name, "set_config") => false,
_ => return None,
};
let (name, arguments) = args.split_first()?;
if let Some(Expr::Value(name)) = function_arg_expr(name).map(unwrap_expr) {
if let Value::SingleQuotedString(name) = &name.value {
if !name.eq_ignore_ascii_case("default_transaction_isolation") {
return None;
}
return Some(if qualified {
IsolationSetting::Default(arguments)
} else {
IsolationSetting::Unknown
});
}
}
Some(IsolationSetting::Unknown)
}
fn identifies(part: &ObjectNamePart, expected: &str) -> bool {
part.as_ident().is_some_and(|name| {
if name.quote_style.is_some() {
name.value == expected
} else {
name.value.eq_ignore_ascii_case(expected)
}
})
}
struct PossibleDefaultIsolation(Option<SqlIsolation>);
impl Visitor for PossibleDefaultIsolation {
type Break = ();
fn pre_visit_expr(&mut self, expr: &Expr) -> ControlFlow<()> {
match expr {
Expr::Function(function) if isolation_setting(function).is_some() => {
self.0 = Some(SqlIsolation::Unknown);
ControlFlow::Break(())
}
_ => ControlFlow::Continue(()),
}
}
fn pre_visit_table_factor(&mut self, table: &TableFactor) -> ControlFlow<()> {
let (name, args) = match table {
TableFactor::Table {
name,
args: Some(args),
..
} => (name, &args.args),
TableFactor::Function { name, args, .. } => (name, args),
_ => return ControlFlow::Continue(()),
};
if classify_call(name, args).is_some() {
self.0 = Some(SqlIsolation::Unknown);
ControlFlow::Break(())
} else {
ControlFlow::Continue(())
}
}
}