mod cache;
use super::super::EnclosingColumnName;
use super::relation::renamed;
use super::single_output;
use crate::idents::ident_key;
pub(in crate::output_label) use cache::LayoutCache;
pub(super) use cache::LayoutKey;
use cache::Layouts;
use sqlparser::ast::{Cte, Query, TableFactor, TableWithJoins};
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) enum SingleOutput {
Named(String),
Unnamed,
}
pub(crate) type OuterCteOutputs<'a> = &'a dyn Fn(&str) -> Option<SingleOutput>;
pub(in crate::output_label) struct Ctes<'a> {
pub(in crate::output_label::scalar) cache: &'a LayoutCache,
pub(in crate::output_label::scalar) local: &'a [Cte],
pub(in crate::output_label::scalar) relations: &'a [TableWithJoins],
pub(in crate::output_label::scalar) before: Option<&'a TableFactor>,
pub(in crate::output_label::scalar) external: Option<EnclosingColumnName<'a>>,
pub(in crate::output_label::scalar) external_ctes: Option<OuterCteOutputs<'a>>,
pub(in crate::output_label::scalar) recursive: bool,
pub(in crate::output_label::scalar) parent: Option<&'a Ctes<'a>>,
pub(in crate::output_label::scalar) active: Option<&'a ActiveCte<'a>>,
}
pub(in crate::output_label::scalar) struct ActiveCte<'a> {
definition: &'a Cte,
previous: Option<&'a ActiveCte<'a>>,
}
impl<'a> Ctes<'a> {
pub(in crate::output_label) fn for_from(
relations: &'a [TableWithJoins],
external: Option<EnclosingColumnName<'a>>,
external_ctes: Option<OuterCteOutputs<'a>>,
cache: &'a LayoutCache,
) -> Self {
Self {
cache,
local: &[],
relations,
before: None,
external,
external_ctes,
recursive: false,
parent: None,
active: None,
}
}
fn with_cte<T: Clone>(
&self,
name: &str,
layouts: &Layouts<T>,
visit: impl FnOnce(&Ctes<'_>, &Cte) -> Option<T>,
fallback: impl FnOnce(Option<SingleOutput>) -> Option<T>,
) -> Option<T> {
let local = std::iter::successors(Some(self), |scope| scope.parent).find_map(|scope| {
scope
.local
.iter()
.enumerate()
.find(|(_, cte)| ident_key(&cte.alias.name) == name)
.map(|entry| (scope, entry))
});
let Some((owner, (index, cte))) = local else {
let external = std::iter::successors(Some(self), |scope| scope.parent)
.find_map(|scope| scope.external_ctes)
.and_then(|lookup| lookup(name));
return fallback(external);
};
if std::iter::successors(self.active, |active| active.previous)
.any(|active| std::ptr::eq(active.definition, cte))
{
return None;
}
self.cache.infer(layouts, LayoutKey::cte(cte, owner), || {
let active = ActiveCte {
definition: cte,
previous: self.active,
};
let visible = Ctes {
local: if owner.recursive {
owner.local
} else {
&owner.local[..index]
},
relations: &[],
before: None,
active: Some(&active),
..*owner
};
visit(&visible, cte)
})
}
pub(in crate::output_label::scalar) fn output(&self, name: &str) -> Option<SingleOutput> {
self.with_cte(
name,
&self.cache.output,
|visible, cte| {
single_output(&cte.query, Some(visible))
.map(|output| renamed(output, Some(&cte.alias)))
},
|external| external,
)
}
pub(in crate::output_label::scalar) fn columns(&self, name: &str) -> Option<Vec<String>> {
self.with_cte(
name,
&self.cache.columns,
|visible, cte| super::relation::query_columns(&cte.query, Some(&cte.alias), visible),
|external| match external? {
SingleOutput::Named(column) => Some(vec![column]),
SingleOutput::Unnamed => None,
},
)
}
}
pub(super) fn query_scope<'a>(query: &'a Query, parent: &'a Ctes<'a>) -> Ctes<'a> {
let mut scope = Ctes::for_from(&[], parent.external, parent.external_ctes, parent.cache);
scope.parent = Some(parent);
scope.active = parent.active;
scope.with_query(query)
}
pub(super) fn root_scope<'a>(
query: &'a Query,
external_ctes: Option<OuterCteOutputs<'a>>,
cache: &'a LayoutCache,
) -> Ctes<'a> {
Ctes::for_from(&[], None, external_ctes, cache).with_query(query)
}
impl<'a> Ctes<'a> {
pub(super) fn relation_prefix(
&self,
relation: &'a TableFactor,
has_prefix: bool,
active: Option<&'a ActiveCte<'a>>,
) -> Self {
Self {
relations: if has_prefix { self.relations } else { &[] },
before: has_prefix.then_some(relation),
active,
..*self
}
}
fn with_query(mut self, query: &'a Query) -> Self {
if let Some(with) = &query.with {
self.local = &with.cte_tables;
self.recursive = with.recursive;
}
self
}
}
pub(crate) fn cte_single_outputs(
query: &Query,
external_ctes: Option<OuterCteOutputs<'_>>,
) -> Vec<(String, Option<SingleOutput>)> {
let Some(with) = &query.with else {
return Vec::new();
};
let cache = LayoutCache::default();
let root = root_scope(query, external_ctes, &cache);
with.cte_tables
.iter()
.map(|cte| {
let name = ident_key(&cte.alias.name);
let output = root.output(&name);
(name, output)
})
.collect()
}