use super::Scope;
use crate::statement_facts::{SqlBareViewRowRead, SqlBareViewRowScope};
pub(super) fn record_correlated_columns(
scopes: &[Scope],
inner: usize,
name: &str,
candidates: &mut [super::super::Candidate],
) {
for scope in &scopes[..inner] {
for index in visible_candidates(scope) {
let read = bare_read(scopes, index, name.to_owned());
add_column_read(&mut candidates[index], read);
}
}
}
pub(in super::super) fn visible_candidates(scope: &Scope) -> impl Iterator<Item = usize> + '_ {
scope
.candidates
.iter()
.chain(
scope
.join_outputs
.values()
.flat_map(|output| &output.candidates),
)
.copied()
}
pub(super) fn add_column_read(candidate: &mut super::super::Candidate, read: SqlBareViewRowRead) {
if !candidate.correlated_columns.contains(&read) {
candidate.correlated_columns.push(read);
}
}
pub(in super::super) fn bare_read(
scopes: &[Scope],
index: usize,
name: String,
) -> SqlBareViewRowRead {
let system_column = matches!(
name.as_str(),
"ctid" | "tableoid" | "xmin" | "xmax" | "cmin" | "cmax"
);
let scopes = scopes
.iter()
.rev()
.map(|scope| {
let mut level = SqlBareViewRowScope {
known_peer_column: scope.known_columns.contains(&name),
..SqlBareViewRowScope::default()
};
let joins = scope
.join_outputs
.iter()
.filter(|(name, _)| scope.bindings.contains_key(*name));
level.opaque_peer = scope.inputs
> scope.known_inputs + scope.physical_inputs.len() + joins.clone().count();
for (_, output) in joins.clone() {
level.known_peer_column |= output.exposes(&name);
level.opaque_peer |= output.opaque_input;
}
let physical = scope
.physical_inputs
.iter()
.chain(joins.flat_map(|(_, output)| &output.physical_inputs));
for input in physical {
if input.candidate == Some(index) {
level.view_input = true;
} else {
input.record_peer(&mut level);
if system_column && input.bare_system_columns {
level.system_column_peers.push(input.relation.clone());
}
}
}
level.peers.sort_unstable();
level.peers.dedup();
level.system_column_peers.sort_unstable();
level.system_column_peers.dedup();
level
})
.collect();
SqlBareViewRowRead { name, scopes }
}
pub(super) fn record_bare_row_read(
candidate: &mut super::super::Candidate,
read: SqlBareViewRowRead,
) {
if read.scopes.iter().any(|scope| {
scope.known_peer_column
|| scope.opaque_peer
|| !scope.peers.is_empty()
|| !scope.aliased_peers.is_empty()
}) {
if !candidate.bare_row_reads.contains(&read) {
candidate.bare_row_reads.push(read);
}
} else {
candidate.other_use = true;
}
}