use std::cmp::Ordering;
use std::fmt;
use std::hash::Hash;
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering as AtomicOrdering};
use datafusion_common::tree_node::TreeNodeRecursion;
use datafusion_common::{DFSchemaRef, Result};
use crate::LogicalPlan;
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct MaterializedCteId(u64);
impl MaterializedCteId {
pub fn next() -> Self {
static NEXT: AtomicU64 = AtomicU64::new(0);
Self(NEXT.fetch_add(1, AtomicOrdering::Relaxed))
}
pub fn as_u64(self) -> u64 {
self.0
}
}
impl fmt::Display for MaterializedCteId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.0)
}
}
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Hash)]
pub enum MaterializedCtePlan {
Cte(MaterializedCte),
Scan(MaterializedCteScan),
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct MaterializedCte {
pub id: MaterializedCteId,
pub name: String,
pub cte: Arc<LogicalPlan>,
pub continuation: Arc<LogicalPlan>,
}
impl MaterializedCte {
pub fn try_new(
id: MaterializedCteId,
name: impl Into<String>,
cte: Arc<LogicalPlan>,
continuation: Arc<LogicalPlan>,
) -> Result<Self> {
let name = name.into();
for scan in MaterializedCteScan::find_in(&continuation, id)? {
scan.schema
.has_equivalent_names_and_types(cte.schema())
.map_err(|e| {
e.context(format!(
"A scan of the materialized CTE {name} does not have the schema of the CTE"
))
})?;
}
Ok(Self {
id,
name,
cte,
continuation,
})
}
pub fn id(&self) -> MaterializedCteId {
self.id
}
pub fn name(&self) -> &str {
&self.name
}
pub fn body(&self) -> &Arc<LogicalPlan> {
&self.cte
}
pub fn continuation(&self) -> &Arc<LogicalPlan> {
&self.continuation
}
pub fn schema(&self) -> &DFSchemaRef {
self.continuation.schema()
}
pub fn scans(&self) -> Result<Vec<MaterializedCteScan>> {
MaterializedCteScan::find_in(&self.continuation, self.id)
}
pub fn with_new_inputs(
&self,
cte: Arc<LogicalPlan>,
continuation: Arc<LogicalPlan>,
) -> Self {
Self {
id: self.id,
name: self.name.clone(),
cte,
continuation,
}
}
}
impl PartialOrd for MaterializedCte {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
match self
.id
.cmp(&other.id)
.then_with(|| self.name.cmp(&other.name))
{
Ordering::Equal if self != other => None,
ord => Some(ord),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct MaterializedCteScan {
pub id: MaterializedCteId,
pub name: String,
pub schema: DFSchemaRef,
}
impl MaterializedCteScan {
pub fn new(
id: MaterializedCteId,
name: impl Into<String>,
schema: DFSchemaRef,
) -> Self {
Self {
id,
name: name.into(),
schema,
}
}
pub fn id(&self) -> MaterializedCteId {
self.id
}
pub fn name(&self) -> &str {
&self.name
}
pub fn schema(&self) -> &DFSchemaRef {
&self.schema
}
pub fn find_in(plan: &LogicalPlan, id: MaterializedCteId) -> Result<Vec<Self>> {
let mut scans = vec![];
plan.apply_with_subqueries(|node| match node {
LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte(cte))
if cte.id == id =>
{
Ok(TreeNodeRecursion::Jump)
}
LogicalPlan::MaterializedCte(MaterializedCtePlan::Scan(scan))
if scan.id == id =>
{
scans.push(scan.clone());
Ok(TreeNodeRecursion::Continue)
}
_ => Ok(TreeNodeRecursion::Continue),
})?;
Ok(scans)
}
}
impl PartialOrd for MaterializedCteScan {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
match self
.id
.cmp(&other.id)
.then_with(|| self.name.cmp(&other.name))
{
Ordering::Equal if self != other => None,
ord => Some(ord),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::logical_plan::builder::LogicalPlanBuilder;
use crate::{EmptyRelation, exists};
use arrow::datatypes::{DataType, Field, Schema};
use datafusion_common::DFSchema;
fn empty(produce_one_row: bool) -> Arc<LogicalPlan> {
Arc::new(LogicalPlan::EmptyRelation(EmptyRelation {
produce_one_row,
schema: Arc::new(DFSchema::empty()),
}))
}
fn schema(data_type: DataType) -> DFSchemaRef {
let schema = Schema::new(vec![Field::new("a", data_type, true)]);
Arc::new(DFSchema::try_from_qualified_schema("c", &schema).unwrap())
}
fn body(data_type: DataType) -> Arc<LogicalPlan> {
Arc::new(LogicalPlan::EmptyRelation(EmptyRelation {
produce_one_row: false,
schema: schema(data_type),
}))
}
fn scan(id: MaterializedCteId, data_type: DataType) -> LogicalPlan {
LogicalPlan::MaterializedCte(MaterializedCtePlan::Scan(MaterializedCteScan::new(
id,
"c",
schema(data_type),
)))
}
#[test]
fn partial_cmp_is_equal_only_for_equal_nodes() {
let id = MaterializedCteId::next();
let a = MaterializedCte {
id,
name: "c".to_string(),
cte: empty(false),
continuation: empty(false),
};
let mut b = a.clone();
assert_eq!(a.partial_cmp(&b), Some(Ordering::Equal));
b.continuation = empty(true);
assert_ne!(a, b);
assert_eq!(a.partial_cmp(&b), None);
let c = MaterializedCte {
id: MaterializedCteId::next(),
..a.clone()
};
assert_eq!(a.partial_cmp(&c), Some(Ordering::Less));
}
#[test]
fn try_new_checks_the_schema_of_the_scans() -> Result<()> {
let id = MaterializedCteId::next();
let cte = MaterializedCte::try_new(
id,
"c",
body(DataType::Int32),
Arc::new(scan(id, DataType::Int32)),
)?;
assert_eq!(cte.id(), id);
assert_eq!(cte.name(), "c");
assert_eq!(cte.schema(), cte.continuation().schema());
assert_eq!(cte.scans()?.len(), 1);
let plan = LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte(cte));
assert_eq!(plan.inputs().len(), 2);
assert_eq!(
plan.display_indent().to_string(),
"MaterializedCte: name=c\n EmptyRelation: rows=0\n MaterializedCteScan: name=c"
);
let err = MaterializedCte::try_new(
id,
"c",
body(DataType::Int32),
Arc::new(scan(id, DataType::Utf8)),
)
.unwrap_err();
assert!(
err.to_string().contains(
"A scan of the materialized CTE c does not have the schema of the CTE"
),
"{err}"
);
MaterializedCte::try_new(
id,
"c",
body(DataType::Int32),
Arc::new(scan(MaterializedCteId::next(), DataType::Utf8)),
)?;
Ok(())
}
#[test]
fn find_in_looks_in_subqueries_and_stops_at_the_same_cte() -> Result<()> {
let id = MaterializedCteId::next();
let other = MaterializedCteId::next();
let plan = LogicalPlanBuilder::from(scan(id, DataType::Int32))
.filter(exists(Arc::new(scan(id, DataType::Int32))))?
.union(scan(other, DataType::Int32))?
.union(LogicalPlan::MaterializedCte(MaterializedCtePlan::Cte(
MaterializedCte::try_new(
id,
"c",
body(DataType::Int32),
Arc::new(scan(id, DataType::Int32)),
)?,
)))?
.build()?;
assert_eq!(MaterializedCteScan::find_in(&plan, id)?.len(), 2);
assert_eq!(MaterializedCteScan::find_in(&plan, other)?.len(), 1);
assert!(
MaterializedCteScan::find_in(&plan, MaterializedCteId::next())?.is_empty()
);
Ok(())
}
}