use crate::fx::FxHashSet;
use crate::idents::{
function_arg_expr, ident_key, object_name_ident, relation_suffix_key, unwrap_expr,
};
use crate::statement_facts::{SqlBareViewRowRead, SqlQualifiedViewKey, SqlViewKeyDependencies};
use crate::statements::keyed_lookups::table::column_reference;
use sqlparser::ast::{BinaryOperator, Expr, JoinConstraint};
mod qualified;
#[derive(Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord)]
pub(super) enum KeyProof {
#[default]
None,
Bare,
Qualified,
}
pub(super) struct KeyTarget<'a> {
pub(super) qualifiers: &'a [&'a str],
pub(super) unaliased: Option<UnaliasedKeyTarget<'a>>,
pub(super) allow_bare: bool,
pub(super) depends_on_view: &'a dyn Fn(&str, &str, &mut SqlViewKeyDependencies) -> bool,
pub(super) may_be_null_extended: &'a dyn Fn(&str, &str, &mut SqlViewKeyDependencies) -> bool,
}
pub(super) struct UnaliasedKeyTarget<'a> {
pub(super) name: &'a str,
pub(super) has_qualified_peer: &'a dyn Fn(&str) -> bool,
pub(super) has_local_qualified_peer: &'a dyn Fn(&str) -> bool,
}
#[derive(Default)]
pub(super) struct PredicateProof {
pub(super) key: KeyProof,
pub(super) conditional: Vec<(KeyProof, KeyConditions)>,
}
#[derive(Default)]
pub(super) struct KeyConditions {
pub(super) peer_relations: Vec<String>,
pub(super) dependencies: SqlViewKeyDependencies,
}
impl KeyConditions {
pub(super) fn into_fact(self, bare_id: Option<SqlBareViewRowRead>) -> SqlQualifiedViewKey {
SqlQualifiedViewKey {
peer_relations: self.peer_relations,
dependencies: self.dependencies,
bare_id,
}
}
}
pub(super) fn proof(
predicate: &Expr,
target: &KeyTarget<'_>,
out: &mut FxHashSet<*const Expr>,
) -> PredicateProof {
let mut found = PredicateProof::default();
record(predicate, target, out, &mut found);
found
}
fn record(
predicate: &Expr,
target: &KeyTarget<'_>,
out: &mut FxHashSet<*const Expr>,
found: &mut PredicateProof,
) {
let Expr::BinaryOp { left, op, right } = unwrap_expr(predicate) else {
return;
};
match op {
BinaryOperator::And => {
record(left, target, out, found);
record(right, target, out, found);
}
BinaryOperator::Eq => {
if let Some((column, conditions)) =
id_side(left, right, target).or_else(|| id_side(right, left, target))
{
out.insert(std::ptr::from_ref(column));
let key = if matches!(column, Expr::Identifier(_)) {
KeyProof::Bare
} else {
KeyProof::Qualified
};
if conditions.peer_relations.is_empty() && conditions.dependencies.is_empty() {
found.key = found.key.max(key);
} else {
found.conditional.push((key, conditions));
}
}
}
_ => {}
}
}
fn id_side<'a>(
value: &'a Expr,
key: &Expr,
target: &KeyTarget<'_>,
) -> Option<(&'a Expr, KeyConditions)> {
let value = unwrap_expr(value);
let mut conditions = KeyConditions::default();
let view_id = match value {
Expr::Identifier(column) => target.allow_bare && ident_key(column) == "id",
Expr::CompoundIdentifier(parts) => qualified::qualified_id(parts, target, &mut conditions),
_ => false,
};
(view_id && independent_key(key, target, &mut conditions, false)).then_some((value, conditions))
}
fn independent_key(
key: &Expr,
target: &KeyTarget<'_>,
conditions: &mut KeyConditions,
under_coalesce: bool,
) -> bool {
match unwrap_expr(key) {
Expr::CompoundIdentifier(parts) => {
let Some((column, qualified)) = column_reference(parts) else {
return false;
};
let column = ident_key(column);
if column == "id" && target.qualifiers.contains(&qualified.as_str())
|| under_coalesce
&& (target.may_be_null_extended)(
&qualified,
&column,
&mut conditions.dependencies,
)
|| (target.depends_on_view)(&qualified, &column, &mut conditions.dependencies)
{
return false;
}
if let Some(unaliased) = target
.unaliased
.as_ref()
.filter(|target| target.name == relation_suffix_key(&qualified))
{
if !(unaliased.has_qualified_peer)(&qualified) {
return false;
}
conditions.peer_relations.push(qualified);
}
true
}
Expr::Cast { expr, .. }
| Expr::UnaryOp {
op: sqlparser::ast::UnaryOperator::Plus | sqlparser::ast::UnaryOperator::Minus,
expr,
} => independent_key(expr, target, conditions, under_coalesce),
Expr::BinaryOp {
left,
op:
BinaryOperator::Plus
| BinaryOperator::Minus
| BinaryOperator::Multiply
| BinaryOperator::Divide
| BinaryOperator::Modulo
| BinaryOperator::PGExp,
right,
} => {
independent_key(left, target, conditions, under_coalesce)
&& independent_key(right, target, conditions, under_coalesce)
}
Expr::Function(function) => super::super::function_clauses::coalesce_arguments(function)
.is_some_and(|args| {
args.iter().all(|arg| {
function_arg_expr(arg)
.is_some_and(|expr| independent_key(expr, target, conditions, true))
})
}),
Expr::TypedString(typed) => !matches!(typed.value.value, sqlparser::ast::Value::Null),
Expr::Value(key) => !matches!(key.value, sqlparser::ast::Value::Null),
_ => false,
}
}
pub(crate) fn using_columns(
constraint: Option<&JoinConstraint>,
) -> impl Iterator<Item = String> + '_ {
match constraint {
Some(JoinConstraint::Using(columns) | JoinConstraint::UsingAlias(columns, _)) => {
columns.as_slice()
}
_ => &[],
}
.iter()
.filter_map(object_name_ident)
.map(ident_key)
}