Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
160 changes: 160 additions & 0 deletions datafusion/expr/src/logical_plan/materialized_cte.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ use std::sync::atomic::{AtomicU64, Ordering as AtomicOrdering};
use datafusion_common::tree_node::{Transformed, TreeNodeRecursion};
use datafusion_common::{
Column, DFSchema, DFSchemaRef, Result, internal_datafusion_err, internal_err,
plan_err,
};

use crate::{Expr, LogicalPlan, Projection};
Expand All @@ -65,8 +66,26 @@ impl MaterializedCteId {
pub fn as_u64(self) -> u64 {
self.0
}

/// The id that a scan decoded by [`MaterializedCteScan::try_from_encoded`]
/// carries until [`MaterializedCte::try_from_encoded`] gives it a new id.
///
/// [`Self::next`] counts up from 0 and does not reach the range of
/// these ids, which have the bit 63 set.
fn encoded(encoded_id: u64) -> Result<Self> {
if encoded_id & DECODED_ID_TAG != 0 {
return plan_err!(
"The id {encoded_id} of an encoded materialized CTE is too large"
);
}
Ok(Self(encoded_id | DECODED_ID_TAG))
}
}

/// The bit that marks the id of a scan that is decoded but not yet bound to
/// its decoded [`MaterializedCte`].
const DECODED_ID_TAG: u64 = 1 << 63;

impl fmt::Display for MaterializedCteId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.0)
Expand Down Expand Up @@ -200,6 +219,34 @@ impl MaterializedCte {
})
}

/// Create a node from the parts of a serialized plan. This constructor
/// is for plan decoders only. To plan a new CTE, use
/// [`MaterializedCteBuilder`].
///
/// `encoded_id` is the id of this node in the serialized plan. The node
/// gets a new id, and the scans in `continuation` that
/// [`MaterializedCteScan::try_from_encoded`] decoded with `encoded_id`
/// get the same new id. A nested node with the same `encoded_id` is
/// decoded first and has already bound its own scans.
///
/// Returns an error if `encoded_id` is out of range, or if a scan of
/// this CTE does not have the names and types of the columns of `body`
/// that it reads.
pub fn try_from_encoded(
encoded_id: u64,
name: impl Into<String>,
body: Arc<LogicalPlan>,
continuation: Arc<LogicalPlan>,
) -> Result<Self> {
let encoded = MaterializedCteId::encoded(encoded_id)?;
let id = MaterializedCteId::next();
let continuation = Self::map_scans(encoded, continuation, |mut scan| {
scan.id = id;
Ok(Transformed::yes(scan))
})?;
Self::try_new(id, name, body, continuation)
}

/// The id that binds the scans in the continuation to this node.
pub fn id(&self) -> MaterializedCteId {
self.id
Expand Down Expand Up @@ -525,6 +572,45 @@ impl MaterializedCteScan {
}
}

/// Create a scan from the parts of a serialized plan. This constructor is
/// for plan decoders only. To plan a new scan, use
/// [`MaterializedCteBuilder::scan`].
///
/// `encoded_id` is the id of the CTE in the serialized plan. The scan is
/// not bound to a CTE of this process until
/// [`MaterializedCte::try_from_encoded`] decodes its CTE with the same
/// `encoded_id`. That call also checks the scan against the body.
///
/// `schema` is the schema of this scan: the columns of the CTE body that
/// `projection` selects, or all of them if `projection` is `None`.
///
/// Returns an error if `encoded_id` is out of range, or if `projection`
/// does not have one index for each column of `schema`.
pub fn try_from_encoded(
encoded_id: u64,
name: impl Into<String>,
schema: DFSchemaRef,
projection: Option<Vec<usize>>,
) -> Result<Self> {
let id = MaterializedCteId::encoded(encoded_id)?;
let name = name.into();
if let Some(projection) = &projection
&& projection.len() != schema.fields().len()
{
return plan_err!(
"The scan of the materialized CTE {name} has {} columns, but its projection has {} indexes",
schema.fields().len(),
projection.len()
);
}
Ok(Self {
id,
name,
schema,
projection,
})
}

/// The id of the [`MaterializedCte`] that this scan reads.
pub fn id(&self) -> MaterializedCteId {
self.id
Expand Down Expand Up @@ -825,6 +911,80 @@ mod tests {
assert_eq!(a.partial_cmp(&c), Some(Ordering::Less));
}

fn encoded_scan(encoded_id: u64) -> Result<LogicalPlan> {
Ok(MaterializedCteScan::try_from_encoded(
encoded_id,
"c",
schema(DataType::Int32),
None,
)?
.into())
}

#[test]
fn try_from_encoded_binds_the_scans_to_a_new_id() -> Result<()> {
// An id that the planner of this process also uses.
let planned = MaterializedCteId::next();

// The inner node is decoded first and binds the scan. The outer node
// has the same encoded id, but it does not take the inner scan.
let inner = MaterializedCte::try_from_encoded(
planned.as_u64(),
"c",
body(DataType::Int32),
Arc::new(encoded_scan(planned.as_u64())?),
)?;
let inner_id = inner.id();
assert_ne!(inner_id, planned);
assert_eq!(
inner.scans()?.iter().map(|s| s.id()).collect::<Vec<_>>(),
vec![inner_id]
);
let outer = MaterializedCte::try_from_encoded(
planned.as_u64(),
"c",
body(DataType::Int32),
Arc::new(inner.into()),
)?;
assert_ne!(outer.id(), inner_id);
assert_eq!(outer.scans()?, vec![]);

// The decoder checks the schema of the scans.
let err = MaterializedCte::try_from_encoded(
3,
"c",
body(DataType::Utf8),
Arc::new(encoded_scan(3)?),
)
.unwrap_err();
assert!(
err.to_string().contains(
"A scan of the materialized CTE c does not have the schema of the CTE"
),
"{err}"
);
Ok(())
}

#[test]
fn try_from_encoded_rejects_an_id_in_the_reserved_range() {
let err = encoded_scan(1 << 63).unwrap_err();
assert!(
err.to_string().contains(
"The id 9223372036854775808 of an encoded materialized CTE is too large"
),
"{err}"
);
let err = MaterializedCte::try_from_encoded(
u64::MAX,
"c",
body(DataType::Int32),
Arc::new(scan(MaterializedCteId::next(), DataType::Int32)),
)
.unwrap_err();
assert!(err.to_string().contains("is too large"), "{err}");
}

#[test]
fn try_new_checks_the_schema_of_the_scans() -> Result<()> {
let id = MaterializedCteId::next();
Expand Down
Loading