use std::sync::Arc;
use arrow::datatypes::Schema;
use datafusion_common::parsers::CompressionTypeVariant;
use datafusion_common::utils::{usize_from_wire, usize_to_wire};
use datafusion_common::{DataFusionError, Result, internal_datafusion_err};
use datafusion_execution::object_store::ObjectStoreUrl;
use datafusion_physical_expr::Partitioning;
use datafusion_physical_expr::projection::{ProjectionExpr, ProjectionExprs};
use datafusion_physical_expr_common::sort_expr::{
optional_ordering_try_from_proto, sort_exprs_try_to_proto,
};
use datafusion_physical_plan::proto::{ExecutionPlanDecodeCtx, ExecutionPlanEncodeCtx};
use datafusion_proto_models::datafusion_common::{
CompressionTypeVariant as ProtoCompressionTypeVariant, Schema as ProtoSchema,
};
use datafusion_proto_models::protobuf;
use crate::file::FileSource;
use crate::file_compression_type::FileCompressionType;
use crate::file_scan_config::{FileScanConfig, FileScanConfigBuilder};
use crate::table_schema::TableSchema;
impl FileScanConfig {
pub fn try_to_proto(
&self,
ctx: &ExecutionPlanEncodeCtx<'_>,
) -> Result<protobuf::FileScanExecConf> {
let Self {
object_store_url,
file_groups,
constraints,
limit,
preserve_order,
output_ordering,
file_compression_type,
file_source,
batch_size,
expr_adapter_factory,
statistics: _,
output_partitioning,
} = self;
if expr_adapter_factory
.as_ref()
.is_some_and(|factory| !factory.is_equivalent_to_default())
{
return datafusion_common::not_impl_err!(
"FileScanConfig with a non-default expr_adapter_factory cannot be serialized"
);
}
let proto_file_groups = file_groups
.iter()
.map(TryInto::try_into)
.collect::<Result<Vec<_>>>()?;
let mut proto_output_ordering = Vec::with_capacity(output_ordering.len());
for order in output_ordering {
let nodes = sort_exprs_try_to_proto(order.iter(), &ctx.expr_ctx())?;
proto_output_ordering.push(protobuf::PhysicalSortExprNodeCollection {
physical_sort_expr_nodes: nodes,
});
}
let proto_output_partitioning = output_partitioning
.as_ref()
.map(|partitioning| partitioning.try_to_proto(&ctx.expr_ctx()))
.transpose()?;
let table_schema = file_source.table_schema();
let file_schema = table_schema.file_schema();
let table_partition_cols = table_schema.table_partition_cols();
let mut fields = file_schema.fields().to_vec();
fields.extend(table_partition_cols.iter().cloned());
let schema = Schema::new(fields).with_metadata(file_schema.metadata.clone());
let projection_exprs = file_source
.projection()
.map(|projection_exprs| {
Ok::<_, DataFusionError>(protobuf::ProjectionExprs {
projections: projection_exprs
.iter()
.map(|expr| {
Ok(protobuf::ProjectionExpr {
alias: expr.alias.to_string(),
expr: Some(ctx.encode_expr(&expr.expr)?),
})
})
.collect::<Result<Vec<_>>>()?,
})
})
.transpose()?;
let proto_file_compression_type =
file_compression_type.is_compressed().then(|| {
let compression: ProtoCompressionTypeVariant =
(*file_compression_type.get_variant()).into();
compression as i32
});
let statistics = self.statistics();
Ok(protobuf::FileScanExecConf {
file_groups: proto_file_groups,
statistics: Some((&statistics).into()),
limit: limit
.map(|limit| usize_to_wire::<u32>(limit, "FileScanConfig", "limit"))
.transpose()?
.map(|limit| protobuf::ScanLimit { limit }),
projection: vec![],
schema: Some((&schema).try_into()?),
table_partition_cols: table_partition_cols
.iter()
.map(|x| x.name().clone())
.collect::<Vec<_>>(),
object_store_url: object_store_url.to_string(),
output_ordering: proto_output_ordering,
constraints: Some(constraints.clone().into()),
batch_size: batch_size.map(|size| size as u64),
projection_exprs,
output_partitioning: proto_output_partitioning,
file_compression_type: proto_file_compression_type,
preserve_order: Some(*preserve_order),
})
}
pub fn try_from_proto(
conf: &protobuf::FileScanExecConf,
ctx: &ExecutionPlanDecodeCtx<'_>,
file_source: Arc<dyn FileSource>,
) -> Result<FileScanConfig> {
let protobuf::FileScanExecConf {
file_groups,
schema: proto_schema,
projection: _,
limit,
statistics,
table_partition_cols: _,
object_store_url,
output_ordering,
constraints,
batch_size,
projection_exprs,
output_partitioning,
file_compression_type,
preserve_order,
} = conf;
let expression_schema = parse_file_scan_schema(proto_schema.as_ref())?;
let decoded_constraints = constraints
.as_ref()
.ok_or_else(|| {
internal_datafusion_err!(
"FileScanExecConf is missing required field 'constraints'"
)
})?
.try_into()?;
let decoded_statistics = statistics
.as_ref()
.ok_or_else(|| {
internal_datafusion_err!(
"FileScanExecConf is missing required field 'statistics'"
)
})?
.try_into()?;
let decoded_file_groups = file_groups
.iter()
.map(TryInto::try_into)
.collect::<Result<Vec<_>>>()?;
let decoded_object_store_url = match object_store_url.is_empty() {
false => ObjectStoreUrl::parse(object_store_url)?,
true => ObjectStoreUrl::local_filesystem(),
};
let mut decoded_output_ordering = Vec::with_capacity(output_ordering.len());
for node_collection in output_ordering {
let protobuf::PhysicalSortExprNodeCollection {
physical_sort_expr_nodes,
} = node_collection;
if let Some(ordering) = optional_ordering_try_from_proto(
physical_sort_expr_nodes,
&ctx.expr_ctx(&expression_schema),
)? {
decoded_output_ordering.push(ordering);
}
}
let decoded_output_partitioning = output_partitioning
.as_ref()
.map(|partitioning| {
Partitioning::try_from_proto(
partitioning,
&ctx.expr_ctx(&expression_schema),
)
})
.transpose()?
.flatten();
let decoded_file_compression_type = file_compression_type
.map(|value| {
let compression =
ProtoCompressionTypeVariant::try_from(value).map_err(|_| {
internal_datafusion_err!("Unknown file compression type: {value}")
})?;
let compression: CompressionTypeVariant = compression.into();
Ok::<_, DataFusionError>(FileCompressionType::from(compression))
})
.transpose()?
.unwrap_or(FileCompressionType::UNCOMPRESSED);
let decoded_file_source = if let Some(proto_projection_exprs) = projection_exprs {
let protobuf::ProjectionExprs { projections } = proto_projection_exprs;
let decoded_projection_exprs: Vec<ProjectionExpr> = projections
.iter()
.map(|proto_expr| {
let protobuf::ProjectionExpr { alias, expr } = proto_expr;
let expr = ctx.decode_expr(
expr.as_ref().ok_or_else(|| {
internal_datafusion_err!("ProjectionExpr missing expr field")
})?,
&expression_schema,
)?;
Ok(ProjectionExpr::new(expr, alias.clone()))
})
.collect::<Result<Vec<_>>>()?;
let projection = ProjectionExprs::new(decoded_projection_exprs);
file_source
.try_pushdown_projection(&projection)?
.unwrap_or(file_source)
} else {
file_source
};
let decoded_limit = limit
.as_ref()
.map(|limit| {
let protobuf::ScanLimit { limit } = limit;
usize_from_wire(*limit, "FileScanConfig", "limit")
})
.transpose()?;
let decoded_batch_size = batch_size
.map(|size| usize_from_wire(size, "FileScanConfig", "batch_size"))
.transpose()?;
if decoded_batch_size == Some(0) {
return datafusion_common::plan_err!(
"FileScanConfig: batch_size must be greater than 0"
);
}
let mut config =
FileScanConfigBuilder::new(decoded_object_store_url, decoded_file_source)
.with_file_groups(decoded_file_groups)
.with_constraints(decoded_constraints)
.with_statistics(decoded_statistics)
.with_limit(decoded_limit)
.with_output_ordering(decoded_output_ordering)
.with_output_partitioning(decoded_output_partitioning)
.with_batch_size(decoded_batch_size)
.with_file_compression_type(decoded_file_compression_type)
.build();
if let Some(preserve_order) = preserve_order {
config.preserve_order = *preserve_order;
}
Ok(config)
}
pub fn parse_table_schema_from_proto(
conf: &protobuf::FileScanExecConf,
) -> Result<TableSchema> {
let schema = parse_file_scan_schema(conf.schema.as_ref())?;
let table_partition_cols = conf
.table_partition_cols
.iter()
.map(|col| Ok(Arc::new(schema.field_with_name(col)?.clone())))
.collect::<Result<Vec<_>>>()?;
let file_schema = Arc::new(
Schema::new(
schema
.fields()
.iter()
.filter(|field| !table_partition_cols.contains(field))
.cloned()
.collect::<Vec<_>>(),
)
.with_metadata(schema.metadata.clone()),
);
Ok(TableSchema::builder(file_schema)
.with_table_partition_cols(table_partition_cols)
.build())
}
}
fn parse_file_scan_schema(schema: Option<&ProtoSchema>) -> Result<Arc<Schema>> {
let proto_schema = schema.ok_or_else(|| {
internal_datafusion_err!("FileScanExecConf is missing required field 'schema'")
})?;
Ok(Arc::new(proto_schema.try_into()?))
}