use super::{
cte_delete, helpers, membership,
relation_references::{cte_name, single_reference},
simple_select_table,
};
use crate::idents::object_name_identity;
use sqlparser::ast::{Query, SetExpr, TableFactor};
use std::collections::BTreeMap;
#[derive(Clone, Copy)]
pub(super) struct VisibleCte<'a> {
pub query: &'a Query,
pub single_reference: bool,
pub has_guard: bool,
}
pub(super) fn check_query<'a>(
query: &'a Query,
inherited: &BTreeMap<String, VisibleCte<'a>>,
positions: super::PlaceholderPositions<'_>,
modes: &super::RowModes<'_>,
out: &mut Vec<super::StatementLockCheck>,
) {
let visible = bindings(query, inherited, true, |query, inherited| {
check_query(query, inherited, positions, modes, out);
});
match query.body.as_ref() {
SetExpr::Insert(stmt)
| SetExpr::Update(stmt)
| SetExpr::Delete(stmt)
| SetExpr::Merge(stmt) => {
let linked = cte_delete_check(query, positions);
let linked_delete = linked.is_some();
out.extend(linked);
super::check_write(stmt, &visible, positions, modes, linked_delete, out)
}
SetExpr::Query(inner) => check_query(inner, &visible, positions, modes, out),
_ => {}
}
}
pub(super) fn bindings<'a>(
query: &'a Query,
inherited: &BTreeMap<String, VisibleCte<'a>>,
count_refs: bool,
mut visit_write: impl FnMut(&'a Query, &BTreeMap<String, VisibleCte<'a>>),
) -> BTreeMap<String, VisibleCte<'a>> {
let mut visible = inherited.clone();
let Some(with) = &query.with else {
return visible;
};
if with.recursive {
let inherited_guards = inherited
.iter()
.map(|(name, binding)| (name.clone(), binding.has_guard))
.collect();
let guards = guard_bindings(query, &inherited_guards);
for cte in &with.cte_tables {
let name = cte_name(cte);
let has_guard = guards[&name];
visible.insert(
name,
VisibleCte {
query: &cte.query,
single_reference: false,
has_guard,
},
);
}
for cte in &with.cte_tables {
visit_write(&cte.query, &visible);
}
return visible;
}
for (index, cte) in with.cte_tables.iter().enumerate() {
visit_write(&cte.query, &visible);
let name = cte_name(cte);
let has_guard = membership::contains_guard(&cte.query, &visible);
let redundant_candidate = count_refs
&& has_guard
&& cte.query.with.is_none()
&& cte.alias.columns.is_empty()
&& !reads_cte(&cte.query, &visible);
let single_reference =
redundant_candidate && single_reference(query, &with.cte_tables[index + 1..], &name);
visible.insert(
name,
VisibleCte {
query: &cte.query,
has_guard,
single_reference,
},
);
}
visible
}
fn reads_cte(query: &Query, visible: &BTreeMap<String, VisibleCte<'_>>) -> bool {
simple_select_table(query).is_some_and(|table| {
matches!(&table.relation, TableFactor::Table { name, .. }
if visible.contains_key(&object_name_identity(name)))
})
}
pub(super) fn guard_bindings(
query: &Query,
inherited: &BTreeMap<String, bool>,
) -> BTreeMap<String, bool> {
let mut visible = inherited.clone();
if let Some(with) = &query.with {
if with.recursive {
for cte in &with.cte_tables {
visible.insert(cte_name(cte), false);
}
while propagate_guards(&with.cte_tables, &mut visible) {}
} else {
for cte in &with.cte_tables {
let has_guard = membership::contains_guard_bindings(&cte.query, &visible);
visible.insert(cte_name(cte), has_guard);
}
}
}
visible
}
fn propagate_guards(ctes: &[sqlparser::ast::Cte], visible: &mut BTreeMap<String, bool>) -> bool {
let mut changed = false;
for cte in ctes {
let name = cte_name(cte);
if !visible[&name] && membership::contains_guard_bindings(&cte.query, visible) {
visible.insert(name, true);
changed = true;
}
}
changed
}
fn cte_delete_check(
query: &Query,
positions: super::PlaceholderPositions<'_>,
) -> Option<super::StatementLockCheck> {
let check = cte_delete::linked_query(query, positions)?;
let locked = super::relation_references::replaceable_cte(query)?;
let table = simple_select_table(locked)?;
let access = helpers::access(&table.relation, None, positions);
Some(super::StatementLockCheck::RedundantSubquery {
relation: access.relation?,
column: check.column,
only: access.only,
requires_non_null: check.requires_non_null,
})
}