use super::super::value;
use crate::idents::{ident_key, object_name_ident};
use sqlparser::ast::{Expr, FunctionArg, FunctionArgExpr, FunctionArguments, Value};
pub(in crate::statements) fn is_fixed_at(
expr: &Expr,
positions: value::PlaceholderPositions<'_>,
) -> bool {
is_fixed_with_columns(expr, positions, &|_| None)
}
pub(in crate::statements) fn is_fixed_with_columns(
expr: &Expr,
positions: value::PlaceholderPositions<'_>,
column: &impl Fn(&Expr) -> Option<FixedCount>,
) -> bool {
matches!(
fixed_count_at(expr, positions, column),
Some(FixedCount::Caller | FixedCount::NonNull)
)
}
#[derive(Clone, Copy, PartialEq)]
pub(in crate::statements) enum FixedCount {
Nullable,
Caller,
NonNull,
}
pub(in crate::statements) fn fixed_count_at(
expr: &Expr,
positions: value::PlaceholderPositions<'_>,
column: &impl Fn(&Expr) -> Option<FixedCount>,
) -> Option<FixedCount> {
match expr {
Expr::Nested(inner) => fixed_count_at(inner, positions, column),
Expr::Value(value) => Some(match value.value {
Value::Null => FixedCount::Nullable,
Value::Placeholder(_) => FixedCount::Caller,
_ => FixedCount::NonNull,
}),
Expr::Identifier(ident) => {
if value::is_placeholder_ident_at(ident, positions) {
Some(FixedCount::Caller)
} else {
column(expr)
}
}
Expr::CompoundIdentifier(_) => column(expr),
Expr::Cast { expr, .. } | Expr::UnaryOp { expr, .. } => {
is_fixed_with_columns(expr, positions, column).then_some(FixedCount::Caller)
}
Expr::BinaryOp { left, right, .. } => (is_fixed_with_columns(left, positions, column)
&& is_fixed_with_columns(right, positions, column))
.then_some(FixedCount::Caller),
Expr::Function(function) => {
let pick = function.name.0.len() == 1
&& object_name_ident(&function.name).is_some_and(|ident| {
ident.quote_style.is_none()
&& ["coalesce", "least", "greatest"].contains(&ident_key(ident).as_str())
});
if !pick {
return None;
}
match &function.args {
FunctionArguments::List(list) => {
let (nullable, non_null) = list.args.iter().try_fold(
(false, false),
|(nullable, non_null), arg| match arg {
FunctionArg::Unnamed(FunctionArgExpr::Expr(expr)) => {
let count = fixed_count_at(expr, positions, column)?;
Some((
nullable || count == FixedCount::Nullable,
non_null || count == FixedCount::NonNull,
))
}
_ => None,
},
)?;
Some(if non_null {
FixedCount::NonNull
} else if nullable {
FixedCount::Nullable
} else {
FixedCount::Caller
})
}
_ => None,
}
}
_ => None,
}
}