datafusion_datasource/file_scan_config/
proto.rs1use std::sync::Arc;
26
27use arrow::datatypes::Schema;
28use datafusion_common::parsers::CompressionTypeVariant;
29use datafusion_common::utils::{usize_from_wire, usize_to_wire};
30use datafusion_common::{DataFusionError, Result, internal_datafusion_err};
31use datafusion_execution::object_store::ObjectStoreUrl;
32use datafusion_physical_expr::Partitioning;
33use datafusion_physical_expr::projection::{ProjectionExpr, ProjectionExprs};
34use datafusion_physical_expr_common::sort_expr::{
35 optional_ordering_try_from_proto, sort_exprs_try_to_proto,
36};
37use datafusion_physical_plan::proto::{ExecutionPlanDecodeCtx, ExecutionPlanEncodeCtx};
38use datafusion_proto_models::datafusion_common::{
39 CompressionTypeVariant as ProtoCompressionTypeVariant, Schema as ProtoSchema,
40};
41use datafusion_proto_models::protobuf;
42
43use crate::file::FileSource;
44use crate::file_compression_type::FileCompressionType;
45use crate::file_scan_config::{FileScanConfig, FileScanConfigBuilder};
46use crate::table_schema::TableSchema;
47
48impl FileScanConfig {
49 pub fn try_to_proto(
57 &self,
58 ctx: &ExecutionPlanEncodeCtx<'_>,
59 ) -> Result<protobuf::FileScanExecConf> {
60 let Self {
64 object_store_url,
65 file_groups,
66 constraints,
67 limit,
68 preserve_order,
69 output_ordering,
70 file_compression_type,
71 file_source,
72 batch_size,
73 expr_adapter_factory,
74 statistics: _,
77 output_partitioning,
78 } = self;
79
80 if expr_adapter_factory
83 .as_ref()
84 .is_some_and(|factory| !factory.is_equivalent_to_default())
85 {
86 return datafusion_common::not_impl_err!(
87 "FileScanConfig with a non-default expr_adapter_factory cannot be serialized"
88 );
89 }
90
91 let proto_file_groups = file_groups
92 .iter()
93 .map(TryInto::try_into)
94 .collect::<Result<Vec<_>>>()?;
95
96 let mut proto_output_ordering = Vec::with_capacity(output_ordering.len());
97 for order in output_ordering {
98 let nodes = sort_exprs_try_to_proto(order.iter(), &ctx.expr_ctx())?;
99 proto_output_ordering.push(protobuf::PhysicalSortExprNodeCollection {
100 physical_sort_expr_nodes: nodes,
101 });
102 }
103
104 let proto_output_partitioning = output_partitioning
105 .as_ref()
106 .map(|partitioning| partitioning.try_to_proto(&ctx.expr_ctx()))
107 .transpose()?;
108
109 let table_schema = file_source.table_schema();
110 let file_schema = table_schema.file_schema();
111 let table_partition_cols = table_schema.table_partition_cols();
112
113 let mut fields = file_schema.fields().to_vec();
116 fields.extend(table_partition_cols.iter().cloned());
117 let schema = Schema::new(fields).with_metadata(file_schema.metadata.clone());
118
119 let projection_exprs = file_source
120 .projection()
121 .map(|projection_exprs| {
122 Ok::<_, DataFusionError>(protobuf::ProjectionExprs {
123 projections: projection_exprs
124 .iter()
125 .map(|expr| {
126 Ok(protobuf::ProjectionExpr {
127 alias: expr.alias.to_string(),
128 expr: Some(ctx.encode_expr(&expr.expr)?),
129 })
130 })
131 .collect::<Result<Vec<_>>>()?,
132 })
133 })
134 .transpose()?;
135
136 let proto_file_compression_type =
137 file_compression_type.is_compressed().then(|| {
138 let compression: ProtoCompressionTypeVariant =
139 (*file_compression_type.get_variant()).into();
140 compression as i32
141 });
142 let statistics = self.statistics();
143
144 Ok(protobuf::FileScanExecConf {
145 file_groups: proto_file_groups,
146 statistics: Some((&statistics).into()),
147 limit: limit
148 .map(|limit| usize_to_wire::<u32>(limit, "FileScanConfig", "limit"))
149 .transpose()?
150 .map(|limit| protobuf::ScanLimit { limit }),
151 projection: vec![],
153 schema: Some((&schema).try_into()?),
154 table_partition_cols: table_partition_cols
155 .iter()
156 .map(|x| x.name().clone())
157 .collect::<Vec<_>>(),
158 object_store_url: object_store_url.to_string(),
159 output_ordering: proto_output_ordering,
160 constraints: Some(constraints.clone().into()),
161 batch_size: batch_size.map(|size| size as u64),
162 projection_exprs,
163 output_partitioning: proto_output_partitioning,
164 file_compression_type: proto_file_compression_type,
165 preserve_order: Some(*preserve_order),
166 })
167 }
168
169 pub fn try_from_proto(
176 conf: &protobuf::FileScanExecConf,
177 ctx: &ExecutionPlanDecodeCtx<'_>,
178 file_source: Arc<dyn FileSource>,
179 ) -> Result<FileScanConfig> {
180 let protobuf::FileScanExecConf {
183 file_groups,
184 schema: proto_schema,
185 projection: _,
188 limit,
189 statistics,
190 table_partition_cols: _,
193 object_store_url,
194 output_ordering,
195 constraints,
196 batch_size,
197 projection_exprs,
198 output_partitioning,
199 file_compression_type,
200 preserve_order,
201 } = conf;
202
203 let expression_schema = parse_file_scan_schema(proto_schema.as_ref())?;
204
205 let decoded_constraints = constraints
206 .as_ref()
207 .ok_or_else(|| {
208 internal_datafusion_err!(
209 "FileScanExecConf is missing required field 'constraints'"
210 )
211 })?
212 .try_into()?;
213 let decoded_statistics = statistics
214 .as_ref()
215 .ok_or_else(|| {
216 internal_datafusion_err!(
217 "FileScanExecConf is missing required field 'statistics'"
218 )
219 })?
220 .try_into()?;
221
222 let decoded_file_groups = file_groups
223 .iter()
224 .map(TryInto::try_into)
225 .collect::<Result<Vec<_>>>()?;
226
227 let decoded_object_store_url = match object_store_url.is_empty() {
228 false => ObjectStoreUrl::parse(object_store_url)?,
229 true => ObjectStoreUrl::local_filesystem(),
230 };
231
232 let mut decoded_output_ordering = Vec::with_capacity(output_ordering.len());
233 for node_collection in output_ordering {
234 let protobuf::PhysicalSortExprNodeCollection {
235 physical_sort_expr_nodes,
236 } = node_collection;
237 if let Some(ordering) = optional_ordering_try_from_proto(
238 physical_sort_expr_nodes,
239 &ctx.expr_ctx(&expression_schema),
240 )? {
241 decoded_output_ordering.push(ordering);
242 }
243 }
244
245 let decoded_output_partitioning = output_partitioning
246 .as_ref()
247 .map(|partitioning| {
248 Partitioning::try_from_proto(
249 partitioning,
250 &ctx.expr_ctx(&expression_schema),
251 )
252 })
253 .transpose()?
254 .flatten();
255
256 let decoded_file_compression_type = file_compression_type
257 .map(|value| {
258 let compression =
259 ProtoCompressionTypeVariant::try_from(value).map_err(|_| {
260 internal_datafusion_err!("Unknown file compression type: {value}")
261 })?;
262 let compression: CompressionTypeVariant = compression.into();
263 Ok::<_, DataFusionError>(FileCompressionType::from(compression))
264 })
265 .transpose()?
266 .unwrap_or(FileCompressionType::UNCOMPRESSED);
267
268 let decoded_file_source = if let Some(proto_projection_exprs) = projection_exprs {
270 let protobuf::ProjectionExprs { projections } = proto_projection_exprs;
271 let decoded_projection_exprs: Vec<ProjectionExpr> = projections
272 .iter()
273 .map(|proto_expr| {
274 let protobuf::ProjectionExpr { alias, expr } = proto_expr;
275 let expr = ctx.decode_expr(
276 expr.as_ref().ok_or_else(|| {
277 internal_datafusion_err!("ProjectionExpr missing expr field")
278 })?,
279 &expression_schema,
280 )?;
281 Ok(ProjectionExpr::new(expr, alias.clone()))
282 })
283 .collect::<Result<Vec<_>>>()?;
284
285 let projection = ProjectionExprs::new(decoded_projection_exprs);
286
287 file_source
288 .try_pushdown_projection(&projection)?
289 .unwrap_or(file_source)
290 } else {
291 file_source
292 };
293
294 let decoded_limit = limit
295 .as_ref()
296 .map(|limit| {
297 let protobuf::ScanLimit { limit } = limit;
298 usize_from_wire(*limit, "FileScanConfig", "limit")
299 })
300 .transpose()?;
301 let decoded_batch_size = batch_size
302 .map(|size| usize_from_wire(size, "FileScanConfig", "batch_size"))
303 .transpose()?;
304 if decoded_batch_size == Some(0) {
305 return datafusion_common::plan_err!(
306 "FileScanConfig: batch_size must be greater than 0"
307 );
308 }
309 let mut config =
310 FileScanConfigBuilder::new(decoded_object_store_url, decoded_file_source)
311 .with_file_groups(decoded_file_groups)
312 .with_constraints(decoded_constraints)
313 .with_statistics(decoded_statistics)
314 .with_limit(decoded_limit)
315 .with_output_ordering(decoded_output_ordering)
316 .with_output_partitioning(decoded_output_partitioning)
317 .with_batch_size(decoded_batch_size)
318 .with_file_compression_type(decoded_file_compression_type)
319 .build();
320
321 if let Some(preserve_order) = preserve_order {
324 config.preserve_order = *preserve_order;
325 }
326 Ok(config)
327 }
328
329 pub fn parse_table_schema_from_proto(
335 conf: &protobuf::FileScanExecConf,
336 ) -> Result<TableSchema> {
337 let schema = parse_file_scan_schema(conf.schema.as_ref())?;
338
339 let table_partition_cols = conf
342 .table_partition_cols
343 .iter()
344 .map(|col| Ok(Arc::new(schema.field_with_name(col)?.clone())))
345 .collect::<Result<Vec<_>>>()?;
346
347 let file_schema = Arc::new(
352 Schema::new(
353 schema
354 .fields()
355 .iter()
356 .filter(|field| !table_partition_cols.contains(field))
357 .cloned()
358 .collect::<Vec<_>>(),
359 )
360 .with_metadata(schema.metadata.clone()),
361 );
362
363 Ok(TableSchema::builder(file_schema)
364 .with_table_partition_cols(table_partition_cols)
365 .build())
366 }
367}
368
369fn parse_file_scan_schema(schema: Option<&ProtoSchema>) -> Result<Arc<Schema>> {
371 let proto_schema = schema.ok_or_else(|| {
372 internal_datafusion_err!("FileScanExecConf is missing required field 'schema'")
373 })?;
374 Ok(Arc::new(proto_schema.try_into()?))
375}