mod group_aliases;
mod input;
mod key_proofs;
mod lateral;
mod natural;
mod nested;
mod null_extension;
mod prefix;
mod using;
use super::{key, Candidate};
use crate::fx::FxHashSet;
use crate::statements::keyed_lookups::query::cte_scope::CteResolver;
pub(super) use nested::JoinOutput;
pub(super) use prefix::{PhysicalInput, Scope};
use sqlparser::ast::{Distinct, Expr, Select};
pub(super) use using::{catalog_only, UsingSource};
pub(super) fn collect_bindings<'a>(
select: &'a Select,
scalar: bool,
ctes: &'a dyn CteResolver,
outer: &'a [Scope],
candidates: &'a mut Vec<Candidate>,
id_refs: &'a mut FxHashSet<*const Expr>,
) -> Scope {
let mut bindings = Bindings::new(ctes, outer, candidates, id_refs);
for root in &select.from {
let sole_input = select.from.len() == 1 && root.joins.is_empty();
bindings.join_root(root, scalar || !sole_input);
}
let mut scope = bindings.finish(select.selection.as_ref());
let cte_output = |name: &str| {
ctes.resolve(name)
.and_then(|entry| entry.single_output.clone())
};
super::query_frame::collect_output_labels(&mut scope, select, outer, Some(&cte_output));
if let Some(Distinct::On(expressions)) = &select.distinct {
scope.distinct_names.extend(
expressions
.iter()
.map(crate::idents::unwrap_expr)
.filter(|expr| matches!(expr, Expr::Identifier(_)))
.map(std::ptr::from_ref),
);
}
group_aliases::collect(&select.group_by, &mut scope);
scope
}
pub(super) struct Bindings<'a> {
ctes: &'a dyn CteResolver,
outer: &'a [Scope],
lateral_ancestors: Vec<Scope>,
candidates: &'a mut Vec<Candidate>,
id_refs: &'a mut FxHashSet<*const Expr>,
scope: Scope,
finished_roots: Scope,
}
impl<'a> Bindings<'a> {
pub(super) fn new(
ctes: &'a dyn CteResolver,
outer: &'a [Scope],
candidates: &'a mut Vec<Candidate>,
id_refs: &'a mut FxHashSet<*const Expr>,
) -> Self {
Self {
ctes,
outer,
lateral_ancestors: Vec::new(),
candidates,
id_refs,
scope: Scope::default(),
finished_roots: Scope::default(),
}
}
pub(super) fn finish(mut self, selection: Option<&Expr>) -> Scope {
self.finished_roots.merge(self.scope);
if let Some(predicate) = selection {
let scope = &self.finished_roots;
key_proofs::record_predicate(
scope,
self.outer,
predicate,
0..self.candidates.len(),
0..self.candidates.len(),
self.candidates,
self.id_refs,
);
}
self.finished_roots
}
pub(super) fn join_root(&mut self, root: &'a sqlparser::ast::TableWithJoins, candidate: bool) {
self.join_chain(root, candidate);
if root.joins.is_empty()
&& matches!(root.relation, sqlparser::ast::TableFactor::Table { .. })
{
if let [input] = self.scope.physical_inputs.as_mut_slice() {
input.bare_system_columns = true;
}
}
self.finished_roots.merge(std::mem::take(&mut self.scope));
}
}