use std::cell::Cell;
use std::sync::Arc;
use arrow::datatypes::{DataType, Field, Schema, SchemaRef};
use datafusion_common::{DataFusionError, Result, internal_err};
use datafusion_execution::TaskContext;
use datafusion_expr::physical_planning_context::ScalarSubqueryResults;
use datafusion_expr::{AggregateUDF, ScalarUDF, WindowUDF};
use datafusion_physical_expr::PhysicalExpr;
use datafusion_physical_expr::expressions::Column;
use datafusion_proto_models::protobuf::{
self, PhysicalExprNode, PhysicalPlanNode, physical_expr_node,
};
use crate::ExecutionPlan;
use crate::empty::EmptyExec;
use crate::proto::{ExecutionPlanDecode, ExecutionPlanEncode};
pub(crate) fn stub_schema() -> SchemaRef {
Arc::new(Schema::new(vec![
Field::new("a", DataType::Int32, true),
Field::new("b", DataType::Int32, true),
]))
}
pub(crate) fn stub_child() -> Arc<dyn ExecutionPlan> {
Arc::new(EmptyExec::new(stub_schema()))
}
pub(crate) fn column_node(name: &str, index: u32) -> PhysicalExprNode {
PhysicalExprNode {
expr_id: None,
expr_type: Some(physical_expr_node::ExprType::Column(
protobuf::PhysicalColumn {
name: name.to_string(),
index,
},
)),
}
}
pub(crate) fn sort_expr_node(
name: &str,
index: u32,
asc: bool,
nulls_first: bool,
) -> PhysicalExprNode {
PhysicalExprNode {
expr_id: None,
expr_type: Some(physical_expr_node::ExprType::Sort(Box::new(
protobuf::PhysicalSortExprNode {
expr: Some(Box::new(column_node(name, index))),
asc,
nulls_first,
},
))),
}
}
pub(crate) fn encoded_child_node() -> PhysicalPlanNode {
PhysicalPlanNode {
physical_plan_type: Some(protobuf::physical_plan_node::PhysicalPlanType::Empty(
protobuf::EmptyExecNode {
schema: None,
partitions: 0,
},
)),
}
}
pub(crate) struct StubPlanEncoder {
plan_calls: Cell<usize>,
expr_calls: Cell<usize>,
fail_plan_on: Option<usize>,
fail_expr_on: Option<usize>,
}
impl StubPlanEncoder {
pub(crate) fn ok() -> Self {
Self {
plan_calls: Cell::new(0),
expr_calls: Cell::new(0),
fail_plan_on: None,
fail_expr_on: None,
}
}
pub(crate) fn failing_on_plan(call: usize) -> Self {
Self {
fail_plan_on: Some(call),
..Self::ok()
}
}
pub(crate) fn failing_on_expr(call: usize) -> Self {
Self {
fail_expr_on: Some(call),
..Self::ok()
}
}
pub(crate) fn plan_calls(&self) -> usize {
self.plan_calls.get()
}
pub(crate) fn expr_calls(&self) -> usize {
self.expr_calls.get()
}
}
impl ExecutionPlanEncode for StubPlanEncoder {
fn encode_plan(&self, _plan: &Arc<dyn ExecutionPlan>) -> Result<PhysicalPlanNode> {
let call = self.plan_calls.get() + 1;
self.plan_calls.set(call);
if Some(call) == self.fail_plan_on {
return Err(DataFusionError::Internal(format!(
"stub plan encode failure on call {call}"
)));
}
Ok(encoded_child_node())
}
fn encode_expr(&self, _expr: &Arc<dyn PhysicalExpr>) -> Result<PhysicalExprNode> {
let call = self.expr_calls.get() + 1;
self.expr_calls.set(call);
if Some(call) == self.fail_expr_on {
return Err(DataFusionError::Internal(format!(
"stub expr encode failure on call {call}"
)));
}
Ok(column_node("child", 0))
}
fn encode_udf(&self, _udf: &ScalarUDF) -> Result<Option<Vec<u8>>> {
Ok(None)
}
fn encode_udaf(&self, _udaf: &AggregateUDF) -> Result<Option<Vec<u8>>> {
Ok(None)
}
fn encode_udwf(&self, _udwf: &WindowUDF) -> Result<Option<Vec<u8>>> {
Ok(None)
}
}
pub(crate) struct StubPlanDecoder {
task_ctx: Arc<TaskContext>,
plan_calls: Cell<usize>,
expr_calls: Cell<usize>,
fail_plan_on: Option<usize>,
fail_expr_on: Option<usize>,
}
impl StubPlanDecoder {
pub(crate) fn ok() -> Self {
Self {
task_ctx: Arc::new(TaskContext::default()),
plan_calls: Cell::new(0),
expr_calls: Cell::new(0),
fail_plan_on: None,
fail_expr_on: None,
}
}
pub(crate) fn failing_on_plan(call: usize) -> Self {
Self {
fail_plan_on: Some(call),
..Self::ok()
}
}
pub(crate) fn failing_on_expr(call: usize) -> Self {
Self {
fail_expr_on: Some(call),
..Self::ok()
}
}
pub(crate) fn plan_calls(&self) -> usize {
self.plan_calls.get()
}
pub(crate) fn expr_calls(&self) -> usize {
self.expr_calls.get()
}
}
impl ExecutionPlanDecode for StubPlanDecoder {
fn decode_plan(&self, _node: &PhysicalPlanNode) -> Result<Arc<dyn ExecutionPlan>> {
let call = self.plan_calls.get() + 1;
self.plan_calls.set(call);
if Some(call) == self.fail_plan_on {
return Err(DataFusionError::Internal(format!(
"stub plan decode failure on call {call}"
)));
}
Ok(stub_child())
}
fn decode_plan_with_scalar_subquery_results(
&self,
node: &PhysicalPlanNode,
_results: ScalarSubqueryResults,
) -> Result<Arc<dyn ExecutionPlan>> {
self.decode_plan(node)
}
fn decode_expr(
&self,
node: &PhysicalExprNode,
_input_schema: &Schema,
) -> Result<Arc<dyn PhysicalExpr>> {
let call = self.expr_calls.get() + 1;
self.expr_calls.set(call);
if Some(call) == self.fail_expr_on {
return Err(DataFusionError::Internal(format!(
"stub expr decode failure on call {call}"
)));
}
match &node.expr_type {
Some(physical_expr_node::ExprType::Column(c)) => {
Ok(Arc::new(Column::new(&c.name, c.index as usize)))
}
_ => Ok(Arc::new(Column::new("a", 0))),
}
}
fn task_ctx(&self) -> &TaskContext {
&self.task_ctx
}
fn decode_udf(&self, name: &str, _payload: Option<&[u8]>) -> Result<Arc<ScalarUDF>> {
internal_err!("stub decoder cannot decode the scalar UDF {name}")
}
fn decode_udaf(
&self,
name: &str,
_payload: Option<&[u8]>,
) -> Result<Arc<AggregateUDF>> {
internal_err!("stub decoder cannot decode the aggregate UDF {name}")
}
fn decode_udwf(&self, name: &str, _payload: Option<&[u8]>) -> Result<Arc<WindowUDF>> {
internal_err!("stub decoder cannot decode the window UDF {name}")
}
}
pub(crate) mod registry_test_plan {
use super::stub_schema;
use crate::execution_plan::{Boundedness, EmissionType};
use crate::proto::{
ExecutionPlanDecodeCtx, ExecutionPlanEncodeCtx, ExtensionPlanFromProto,
};
use crate::{
DisplayAs, DisplayFormatType, ExecutionPlan, PlanProperties,
SendableRecordBatchStream,
};
use datafusion_common::tree_node::TreeNodeRecursion;
use datafusion_common::{Result, internal_err};
use datafusion_execution::TaskContext;
use datafusion_physical_expr::{EquivalenceProperties, Partitioning};
use datafusion_proto_models::protobuf::PhysicalPlanNode;
use std::fmt::Formatter;
use std::sync::Arc;
fn stub_properties() -> Arc<PlanProperties> {
Arc::new(PlanProperties::new(
EquivalenceProperties::new(stub_schema()),
Partitioning::UnknownPartitioning(1),
EmissionType::Incremental,
Boundedness::Bounded,
))
}
macro_rules! extension_plan {
($name:ident, $plan_name:literal) => {
#[derive(Debug)]
pub(crate) struct $name {
pub(crate) payload: String,
pub(crate) children: Vec<Arc<dyn ExecutionPlan>>,
properties: Arc<PlanProperties>,
}
impl $name {
pub(crate) fn new(
payload: impl Into<String>,
children: Vec<Arc<dyn ExecutionPlan>>,
) -> Self {
Self {
payload: payload.into(),
children,
properties: stub_properties(),
}
}
}
impl DisplayAs for $name {
fn fmt_as(
&self,
_t: DisplayFormatType,
f: &mut Formatter,
) -> std::fmt::Result {
write!(f, "{}({})", $plan_name, self.payload)
}
}
impl ExecutionPlan for $name {
fn name(&self) -> &str {
$plan_name
}
fn properties(&self) -> &Arc<PlanProperties> {
&self.properties
}
fn children(&self) -> Vec<&Arc<dyn ExecutionPlan>> {
self.children.iter().collect()
}
fn apply_expressions(
&self,
_f: &mut dyn FnMut(
&Arc<dyn crate::PhysicalExpr>,
) -> Result<TreeNodeRecursion>,
) -> Result<TreeNodeRecursion> {
Ok(TreeNodeRecursion::Continue)
}
fn with_new_children(
self: Arc<Self>,
children: Vec<Arc<dyn ExecutionPlan>>,
) -> Result<Arc<dyn ExecutionPlan>> {
Ok(Arc::new(Self::new(self.payload.clone(), children)))
}
fn execute(
&self,
_partition: usize,
_context: Arc<TaskContext>,
) -> Result<SendableRecordBatchStream> {
internal_err!("{} is a serde-only test stub", $plan_name)
}
fn try_to_proto(
&self,
ctx: &ExecutionPlanEncodeCtx<'_>,
) -> Result<Option<PhysicalPlanNode>> {
Ok(Some(ctx.extension_node::<Self>(
self.payload.as_bytes().to_vec(),
self.children(),
)?))
}
}
impl ExtensionPlanFromProto for $name {
const NAME: &'static str = $plan_name;
fn try_from_proto(
node: &PhysicalPlanNode,
ctx: &ExecutionPlanDecodeCtx<'_>,
) -> Result<Arc<dyn ExecutionPlan>> {
let extension = crate::expect_plan_variant!(
node,
datafusion_proto_models::protobuf::physical_plan_node::PhysicalPlanType::Extension,
"Extension"
);
let children = ctx.decode_children(&extension.inputs)?;
let Ok(payload) = std::str::from_utf8(&extension.node) else {
return internal_err!("{} payload is not UTF-8", $plan_name);
};
Ok(Arc::new(Self::new(payload, children)))
}
}
};
}
extension_plan!(RegisteredExec, "datafusion-test.RegisteredExec");
extension_plan!(RegisteredExecClone, "datafusion-test.RegisteredExec");
extension_plan!(OtherRegisteredExec, "datafusion-test.OtherRegisteredExec");
extension_plan!(UnnamedExec, "");
}
pub(crate) struct UnreachablePlanDecoder {
task_ctx: Arc<TaskContext>,
}
impl UnreachablePlanDecoder {
pub(crate) fn new() -> Self {
Self {
task_ctx: Arc::new(TaskContext::default()),
}
}
}
impl ExecutionPlanDecode for UnreachablePlanDecoder {
fn decode_plan(&self, _node: &PhysicalPlanNode) -> Result<Arc<dyn ExecutionPlan>> {
unreachable!("decode_plan must not be reached when the node is rejected")
}
fn decode_plan_with_scalar_subquery_results(
&self,
_node: &PhysicalPlanNode,
_results: ScalarSubqueryResults,
) -> Result<Arc<dyn ExecutionPlan>> {
unreachable!("decode_plan must not be reached when the node is rejected")
}
fn decode_expr(
&self,
_node: &PhysicalExprNode,
_input_schema: &Schema,
) -> Result<Arc<dyn PhysicalExpr>> {
unreachable!("decode_expr must not be reached when the node is rejected")
}
fn task_ctx(&self) -> &TaskContext {
&self.task_ctx
}
fn decode_udf(&self, _name: &str, _payload: Option<&[u8]>) -> Result<Arc<ScalarUDF>> {
unreachable!("decode_udf must not be reached when the node is rejected")
}
fn decode_udaf(
&self,
_name: &str,
_payload: Option<&[u8]>,
) -> Result<Arc<AggregateUDF>> {
unreachable!("decode_udaf must not be reached when the node is rejected")
}
fn decode_udwf(
&self,
_name: &str,
_payload: Option<&[u8]>,
) -> Result<Arc<WindowUDF>> {
unreachable!("decode_udwf must not be reached when the node is rejected")
}
}