rdettai commented on a change in pull request #1141: URL: https://github.com/apache/arrow-datafusion/pull/1141#discussion_r739051018
########## File path: datafusion/src/datasource/listing/helpers.rs ########## @@ -0,0 +1,729 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +//! Helper functions for the table implementation + +use std::sync::Arc; + +use arrow::{ + array::{ + Array, ArrayBuilder, ArrayRef, Date64Array, Date64Builder, StringArray, + StringBuilder, UInt64Array, UInt64Builder, + }, + datatypes::{DataType, Field, Schema}, + record_batch::RecordBatch, +}; +use chrono::{TimeZone, Utc}; +use futures::{ + stream::{self}, + StreamExt, TryStreamExt, +}; +use log::debug; + +use crate::{ + error::Result, + execution::context::ExecutionContext, + logical_plan::{self, Expr}, + physical_plan::functions::Volatility, + scalar::ScalarValue, +}; + +use crate::datasource::{ + object_store::{FileMeta, ObjectStore, SizedFile}, + MemTable, PartitionedFile, PartitionedFileStream, +}; + +const FILE_SIZE_COLUMN_NAME: &str = "_df_part_file_size_"; +const FILE_PATH_COLUMN_NAME: &str = "_df_part_file_path_"; +const FILE_MODIFIED_COLUMN_NAME: &str = "_df_part_file_modified_"; + +/// Check whether the given expression can be resolved using only the columns `col_names`. +/// This means that if this function returns true: +/// - the table provider can filter the table partition values with this expression +/// - the expression can be marked as `TableProviderFilterPushDown::Exact` once this filtering +/// was performed +pub fn expr_applicable_for_cols(col_names: &[String], expr: &Expr) -> bool { + match expr { + // leaf + Expr::Literal(_) => true, + // TODO how to handle qualified / unqualified names? + Expr::Column(logical_plan::Column { ref name, .. }) => col_names.contains(name), + // unary + Expr::Alias(child, _) + | Expr::Not(child) + | Expr::IsNotNull(child) + | Expr::IsNull(child) + | Expr::Negative(child) + | Expr::Cast { expr: child, .. } + | Expr::TryCast { expr: child, .. } => expr_applicable_for_cols(col_names, child), + // binary + Expr::BinaryExpr { + ref left, + ref right, + .. + } => { + expr_applicable_for_cols(col_names, left) + && expr_applicable_for_cols(col_names, right) + } + // ternary + Expr::Between { + expr: item, + low, + high, + .. + } => { + expr_applicable_for_cols(col_names, item) + && expr_applicable_for_cols(col_names, low) + && expr_applicable_for_cols(col_names, high) + } + // variadic + Expr::ScalarFunction { fun, args } => match fun.volatility() { + Volatility::Immutable => args + .iter() + .all(|arg| expr_applicable_for_cols(col_names, arg)), + // TODO: Stable functions could be `applicable`, but that would require access to the context + Volatility::Stable => false, + Volatility::Volatile => false, + }, + Expr::ScalarUDF { fun, args } => match fun.signature.volatility { + Volatility::Immutable => args + .iter() + .all(|arg| expr_applicable_for_cols(col_names, arg)), + // TODO: Stable functions could be `applicable`, but that would require access to the context + Volatility::Stable => false, + Volatility::Volatile => false, + }, + Expr::InList { + expr: item, list, .. + } => { + expr_applicable_for_cols(col_names, item) + && list.iter().all(|e| expr_applicable_for_cols(col_names, e)) + } + Expr::Case { + expr, + when_then_expr, + else_expr, + } => { + let expr_constant = expr + .as_ref() + .map(|e| expr_applicable_for_cols(col_names, e)) + .unwrap_or(true); + let else_constant = else_expr + .as_ref() + .map(|e| expr_applicable_for_cols(col_names, e)) + .unwrap_or(true); + let when_then_constant = when_then_expr.iter().all(|(w, th)| { + expr_applicable_for_cols(col_names, w) + && expr_applicable_for_cols(col_names, th) + }); + expr_constant && else_constant && when_then_constant + } + // TODO other expressions are not handled yet: + // - AGGREGATE, WINDOW and SORT should not end up in filter conditions, except maybe in some edge cases + // - Can `Wildcard` be considered as a `Literal`? + // - ScalarVariable could be `applicable`, but that would require access to the context + _ => false, + } +} + +/// Partition the list of files into `n` groups +pub fn split_files( + partitioned_files: Vec<PartitionedFile>, + n: usize, +) -> Vec<Vec<PartitionedFile>> { + if partitioned_files.is_empty() { + return vec![]; + } + let chunk_size = (partitioned_files.len() + n - 1) / n; + partitioned_files + .chunks(chunk_size) + .map(|c| c.to_vec()) + .collect() +} + +/// Discover the partitions on the given path and prune out files +/// that belong to irrelevant partitions using `filters` expressions. +/// `filters` might contain expressions that can be resolved only at the +/// file level (e.g. Parquet row group pruning). +/// +/// TODO for tables with many files (10k+), it will usually more efficient +/// to first list the folders relative to the first partition dimension, +/// prune those, then list only the contain of the remaining folders. +pub async fn pruned_partition_list( + store: &dyn ObjectStore, + table_path: &str, + filters: &[Expr], + file_extension: &str, + table_partition_cols: &[String], +) -> Result<PartitionedFileStream> { + // if no partition col => simply list all the files + if table_partition_cols.is_empty() { + return Ok(Box::pin( + store + .list_file_with_suffix(table_path, file_extension) + .await? + .map(|f| { + Ok(PartitionedFile { + partition_values: vec![], + file_meta: f?, + }) + }), + )); + } + + let applicable_filters: Vec<_> = filters + .iter() + .filter(|f| expr_applicable_for_cols(table_partition_cols, f)) + .collect(); + let stream_path = table_path.to_owned(); + if applicable_filters.is_empty() { + // parse the partition values while listing all the files + // TODO we might avoid parsing the partition values if they are not used in any projection Review comment: Agreed, I'll update the comment and remove the `// TODO` -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected]
