Skip to content
Merged
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
3 changes: 2 additions & 1 deletion src/duckdb/extension/parquet/parquet_multi_file_info.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -257,7 +257,8 @@ void ParquetScanFunction::AddNamedParameters(TableFunction &table_function) {
.Add("can_have_nan", LogicalType::BOOLEAN)
.Add("prefetch_strategy", LogicalType::VARCHAR)
.Add("utf8_validation", LogicalType::VARCHAR)
.Add("int96_as", LogicalType::VARCHAR);
.Add("int96_as", LogicalType::VARCHAR)
.Add("maximum_files_for_stats", LogicalType::UBIGINT);
};
// the multi-file function already declares options of its own - the single-file function declares none
auto &signature = table_function.GetSignature();
Expand Down
8 changes: 4 additions & 4 deletions src/duckdb/generated_extension_loader_package_build.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ int32_t duckdb_extension_core_functions_describe(duckdb_extension_descriptor *de
descriptor->version = 1;
descriptor->name = "core_functions";
descriptor->extension_version = EXT_VERSION_CORE_FUNCTIONS;
descriptor->api_version = "v2.0.1-alpha55117";
descriptor->api_version = "v2.0.1-alpha55228";
descriptor->entry_cpp = (void (*)(void))core_functions_duckdb_cpp_init;
return 0;
}
Expand Down Expand Up @@ -78,7 +78,7 @@ int32_t duckdb_extension_parquet_describe(duckdb_extension_descriptor *descripto
descriptor->version = 1;
descriptor->name = "parquet";
descriptor->extension_version = EXT_VERSION_PARQUET;
descriptor->api_version = "v2.0.1-alpha55117";
descriptor->api_version = "v2.0.1-alpha55228";
descriptor->entry_cpp = (void (*)(void))parquet_duckdb_cpp_init;
return 0;
}
Expand Down Expand Up @@ -111,7 +111,7 @@ int32_t duckdb_extension_icu_describe(duckdb_extension_descriptor *descriptor) {
descriptor->version = 1;
descriptor->name = "icu";
descriptor->extension_version = EXT_VERSION_ICU;
descriptor->api_version = "v2.0.1-alpha55117";
descriptor->api_version = "v2.0.1-alpha55228";
descriptor->entry_cpp = (void (*)(void))icu_duckdb_cpp_init;
return 0;
}
Expand Down Expand Up @@ -144,7 +144,7 @@ int32_t duckdb_extension_json_describe(duckdb_extension_descriptor *descriptor)
descriptor->version = 1;
descriptor->name = "json";
descriptor->extension_version = EXT_VERSION_JSON;
descriptor->api_version = "v2.0.1-alpha55117";
descriptor->api_version = "v2.0.1-alpha55228";
descriptor->entry_cpp = (void (*)(void))json_duckdb_cpp_init;
return 0;
}
Expand Down
41 changes: 40 additions & 1 deletion src/duckdb/src/common/multi_file/multi_file_reader.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -540,6 +540,11 @@ bool MultiFileReader::ParseOption(const Identifier &key, const Value &val, Multi
options.SetColumnStatistics(key, val);
} else if (key == "maximum_sample_files") {
options.SetMaximumSampleFiles(key, val);
} else if (key == "maximum_files_for_stats") {
if (val.IsNull()) {
throw InvalidInputException("Cannot use NULL as argument for %s", key);
}
options.maximum_files_for_stats = val.DefaultCastAs(LogicalType::UBIGINT).GetValue<idx_t>();
} else if (key == "hive_types_autocast" || key == "hive_type_autocast") {
if (val.IsNull()) {
throw InvalidInputException("Cannot use NULL as argument for %s", key);
Expand Down Expand Up @@ -1067,7 +1072,41 @@ MultiFileReaderBindData MultiFileReader::BindReader(ClientContext &context, vect
if (file_options.maximum_sample_files > 1) {
return BindSampledReader(context, return_types, names, files, result, options, file_options);
}
return BindFirstReader(context, return_types, names, files, result, options, file_options);
auto bind_data = BindFirstReader(context, return_types, names, files, result, options, file_options);
ReadFilesForStatistics(context, files, result, options, file_options);
return bind_data;
}

void MultiFileReader::ReadFilesForStatistics(ClientContext &context, MultiFileList &files, MultiFileBindData &result,
BaseFileReaderOptions &options, MultiFileOptions &file_options) {
auto max_files = file_options.maximum_files_for_stats;
if (max_files == 0 || !result.union_readers.empty()) {
return;
}
// a single file bound on its own already has its statistics from the initial reader
const idx_t min_files = result.initial_reader ? 2 : 1;
auto count = files.GetFileCount(max_files + 1);
if (count.type != FileExpansionType::ALL_FILES_EXPANDED || count.count < min_files || count.count > max_files) {
return;
}
// an open first file is reused: only the others are read. A file that cannot be read gives no statistics rather
// than failing the bind: the scan reports it
auto all_files = files.GetAllFiles();
if (result.initial_reader && result.initial_reader->GetFileName() != all_files[0].path) {
return;
}
vector<OpenFileInfo> unread_files(all_files.begin() + (result.initial_reader ? 1 : 0), all_files.end());
auto readers = UnionByName::ReadUnionData(context, unread_files, options, file_options, *this, *result.interface,
true, TaskSchedulerType::ASYNC);
for (auto &reader : readers) {
if (!reader) {
return;
}
}
if (result.initial_reader) {
readers.insert(readers.begin(), result.initial_reader->GetUnionData(0));
}
std::move(readers.begin(), readers.end(), std::back_inserter(result.union_readers));
}

MultiFileReaderBindData MultiFileReader::BindFirstReader(ClientContext &context, vector<LogicalType> &return_types,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -593,6 +593,12 @@ void TableFunctionMultiFileWrapper::GetVirtualColumns(ClientContext &context, Mu
}
}

void TableFunctionMultiFileWrapper::ReadFilesForStatistics(ClientContext &context, MultiFileBindData &bind_data) {
auto &data = bind_data.bind_data->Cast<TableFunctionMultiFileData>();
bind_data.multi_file_reader->ReadFilesForStatistics(context, *bind_data.file_list, bind_data, data.options,
bind_data.file_options);
}

void TableFunctionMultiFileWrapper::FinalizeBindData(MultiFileBindData &multi_file_data) {
auto &data = multi_file_data.bind_data->Cast<TableFunctionMultiFileData>();
if (multi_file_data.initial_reader) {
Expand Down
44 changes: 32 additions & 12 deletions src/duckdb/src/common/multi_file/union_by_name.cpp
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
#include "duckdb/common/multi_file/union_by_name.hpp"
#include "duckdb/common/multi_file/multi_file_function.hpp"
#include "duckdb/parallel/task_executor.hpp"
#include "duckdb/common/error_data.hpp"

namespace duckdb {

Expand All @@ -9,14 +10,24 @@ class UnionByReaderTask : public BaseExecutorTask {
UnionByReaderTask(TaskExecutor &executor, ClientContext &context, const OpenFileInfo &file, idx_t file_idx,
vector<shared_ptr<BaseUnionData>> &readers, BaseFileReaderOptions &options,
MultiFileOptions &file_options, MultiFileReader &multi_file_reader,
MultiFileReaderInterface &interface)
MultiFileReaderInterface &interface, bool ignore_errors)
: BaseExecutorTask(executor), context(context), file(file), file_idx(file_idx), readers(readers),
options(options), file_options(file_options), multi_file_reader(multi_file_reader), interface(interface) {
options(options), file_options(file_options), multi_file_reader(multi_file_reader), interface(interface),
ignore_errors(ignore_errors) {
}

void ExecuteTask() override {
auto reader = multi_file_reader.CreateReader(context, file, options, file_options, interface);
readers[file_idx] = reader->GetUnionData(file_idx);
try {
auto reader = multi_file_reader.CreateReader(context, file, options, file_options, interface);
if (reader) {
readers[file_idx] = reader->GetUnionData(file_idx);
}
} catch (std::exception &ex) {
ErrorData error(ex);
if (!ignore_errors || error.Type() == ExceptionType::INTERRUPT) {
throw;
}
}
}

string TaskType() const override {
Expand All @@ -32,26 +43,35 @@ class UnionByReaderTask : public BaseExecutorTask {
MultiFileOptions &file_options;
MultiFileReader &multi_file_reader;
MultiFileReaderInterface &interface;
bool ignore_errors;
};

vector<shared_ptr<BaseUnionData>> UnionByName::UnionCols(ClientContext &context, const vector<OpenFileInfo> &files,
vector<LogicalType> &union_col_types,
vector<Identifier> &union_col_names,
BaseFileReaderOptions &options, MultiFileOptions &file_options,
MultiFileReader &multi_file_reader,
MultiFileReaderInterface &interface) {
vector<shared_ptr<BaseUnionData>>
UnionByName::ReadUnionData(ClientContext &context, const vector<OpenFileInfo> &files, BaseFileReaderOptions &options,
MultiFileOptions &file_options, MultiFileReader &multi_file_reader,
MultiFileReaderInterface &interface, bool ignore_errors, TaskSchedulerType scheduler_type) {
vector<shared_ptr<BaseUnionData>> union_readers;
union_readers.resize(files.size());

TaskExecutor executor(context);
TaskExecutor executor(context, scheduler_type);
// schedule tasks for all files
for (idx_t file_idx = 0; file_idx < files.size(); ++file_idx) {
auto task = make_uniq<UnionByReaderTask>(executor, context, files[file_idx], file_idx, union_readers, options,
file_options, multi_file_reader, interface);
file_options, multi_file_reader, interface, ignore_errors);
executor.ScheduleTask(std::move(task));
}
// complete all tasks
executor.WorkOnTasks();
return union_readers;
}

vector<shared_ptr<BaseUnionData>> UnionByName::UnionCols(ClientContext &context, const vector<OpenFileInfo> &files,
vector<LogicalType> &union_col_types,
vector<Identifier> &union_col_names,
BaseFileReaderOptions &options, MultiFileOptions &file_options,
MultiFileReader &multi_file_reader,
MultiFileReaderInterface &interface) {
auto union_readers = ReadUnionData(context, files, options, file_options, multi_file_reader, interface);

// now combine the result schemas
interface.CombineSchemas(context, union_readers, file_options.union_by_name, union_col_types, union_col_names);
Expand Down
6 changes: 3 additions & 3 deletions src/duckdb/src/function/table/version/pragma_version.cpp
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
#ifndef DUCKDB_PATCH_VERSION
#define DUCKDB_PATCH_VERSION "1-alpha55117"
#define DUCKDB_PATCH_VERSION "1-alpha55228"
#endif
#ifndef DUCKDB_MINOR_VERSION
#define DUCKDB_MINOR_VERSION 0
Expand All @@ -8,10 +8,10 @@
#define DUCKDB_MAJOR_VERSION 2
#endif
#ifndef DUCKDB_VERSION
#define DUCKDB_VERSION "v2.0.1-alpha55117"
#define DUCKDB_VERSION "v2.0.1-alpha55228"
#endif
#ifndef DUCKDB_SOURCE_ID
#define DUCKDB_SOURCE_ID "331f91a84f"
#define DUCKDB_SOURCE_ID "234b108bd9"
#endif
#include "duckdb/function/table/system_functions.hpp"
#include "duckdb/main/database.hpp"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,10 @@ struct MultiFileReaderInterface {
unique_ptr<BaseFileReaderOptions> options) = 0;
virtual void BindReader(ClientContext &context, vector<LogicalType> &return_types, vector<Identifier> &names,
MultiFileBindData &bind_data) = 0;
//! After a custom MultiFileReader::Bind, open the files for their statistics (maximum_files_for_stats) with the
//! reader options, which only the interface holds
virtual void ReadFilesForStatistics(ClientContext &context, MultiFileBindData &bind_data) {
}
//! Combine the schemas of a set of files that were bound individually into a single schema
//! The default implementation combines the return types of the files by name
virtual void CombineSchemas(ClientContext &context, const vector<shared_ptr<BaseUnionData>> &union_data,
Expand Down Expand Up @@ -170,6 +174,7 @@ class MultiFileFunction : public TableFunction {
}
result->multi_file_reader->BindOptions(result->file_options, *result->file_list, result->types,
result->names, result->reader_bind);
interface.ReadFilesForStatistics(context, *result);
bound_on_first_file = false;
} else {
result->file_options.AutoDetectHivePartitioning(*result->file_list, context);
Expand Down Expand Up @@ -1139,6 +1144,30 @@ class MultiFileFunction : public TableFunction {
return result;
}

//! Whether a column and its nested fields read the file fields of the same name
static bool KeepsFileNames(const MultiFileColumnDefinition &column) {
if (!column.identifier.IsNull() && (column.identifier.type().id() != LogicalTypeId::VARCHAR ||
column.identifier.GetValue<string>() != column.name.GetIdentifierName())) {
return false;
}
for (auto &child : column.children) {
if (!KeepsFileNames(child)) {
return false;
}
}
return true;
}

//! Whether the "schema" option maps the named output column onto the file column of the same name
static bool SchemaKeepsFileNames(const vector<MultiFileColumnDefinition> &schema, const Identifier &col_name) {
for (auto &column : schema) {
if (column.name == col_name) {
return KeepsFileNames(column);
}
}
return false;
}

static unique_ptr<BaseStatistics> MultiFileScanStatsInternal(ClientContext &context,
TableFunctionGetStatisticsInput &input) {
auto &bind_data = input.bind_data->Cast<MultiFileBindData>();
Expand Down Expand Up @@ -1187,39 +1216,66 @@ class MultiFileFunction : public TableFunction {
// A physical shadow's bounds do not describe the generated path. Explicit scan statistics above still do.
return nullptr;
}
if (!opened_a_file) {
if (!bind_data.file_options.schema.empty() && !SchemaKeepsFileNames(bind_data.file_options.schema, col_name)) {
// The files' statistics are looked up by output name, not through the schema's column mapping
return nullptr;
}
if (!opened_a_file && bind_data.union_readers.empty()) {
return nullptr;
}
// NOTE: we do not want to parse the file metadata for the sole purpose of getting column statistics
const bool multiple_files = bind_data.file_list->GetExpandResult() == FileExpandResult::MULTIPLE_FILES;
if (multiple_files && !bind_data.file_options.union_by_name) {
// multiple files, but no union_by_name: no luck!
// multiple files: only if every file was opened at bind (union_by_name, maximum_sample_files or
// maximum_files_for_stats)
if (multiple_files && bind_data.union_readers.size() != bind_data.file_list->GetTotalFileCount()) {
return nullptr;
}
unique_ptr<BaseStatistics> result;
try {
result = bind_data.initial_reader->GetStatistics(context, col_name);
if (result && !bind_data.file_options.bound_schema.empty() &&
!bind_data.MatchesPhysicalColumn(primary_index, col_name, result->GetType())) {
// Check the whole root before interpreting an extracted child's positional statistics.
return nullptr;
auto get_statistics = [&](BaseUnionData &reader) {
unique_ptr<BaseStatistics> stats;
try {
stats = reader.GetStatistics(context, col_name);
} catch (std::exception &ex) {
// statistics that cannot be decoded just mean there are none - the data itself may still read fine
if (ErrorData(ex).Type() == ExceptionType::INTERRUPT) {
throw;
}
return unique_ptr<BaseStatistics>();
}
if (result && multiple_files) {
for (idx_t i = 1; i < bind_data.union_readers.size(); i++) {
auto &union_reader = *bind_data.union_readers[i];
auto stats = union_reader.GetStatistics(context, col_name);
if (!stats || result->GetType() != stats->GetType()) {
return nullptr;
}
if (stats && (stats->GetType() != bind_data.types[primary_index] ||
(!bind_data.file_options.bound_schema.empty() &&
!bind_data.MatchesPhysicalColumn(primary_index, col_name, stats->GetType())))) {
// Positional child statistics require the physical root to match the scan's output layout.
return unique_ptr<BaseStatistics>();
}
return stats;
};
unique_ptr<BaseStatistics> result;
if (multiple_files) {
for (auto &union_reader : bind_data.union_readers) {
auto rows = union_reader->TryGetCardinalityEstimate();
if (rows.IsValid() && rows.GetIndex() == 0) {
// an empty file has no statistics, and no values the merged bounds must cover
continue;
}
auto stats = get_statistics(*union_reader);
if (!stats) {
return nullptr;
}
if (!result) {
result = std::move(stats);
} else {
result->Merge(*stats);
}
}
} catch (std::exception &ex) {
// undecodable statistics of one of multiple files just mean there are none - the data may still read fine
if (!multiple_files || ErrorData(ex).Type() == ExceptionType::INTERRUPT) {
throw;
} else {
result = bind_data.initial_reader ? bind_data.initial_reader->GetStatistics(context, col_name)
: bind_data.union_readers[0]->GetStatistics(context, col_name);
if (result && (result->GetType() != bind_data.types[primary_index] ||
(!bind_data.file_options.bound_schema.empty() &&
!bind_data.MatchesPhysicalColumn(primary_index, col_name, result->GetType())))) {
// Check the whole root before interpreting an extracted child's positional statistics.
return nullptr;
}
return nullptr;
}
if (!result || !column_index.IsPushdownExtract()) {
return result;
Expand Down Expand Up @@ -1299,8 +1355,13 @@ class MultiFileFunction : public TableFunction {
if (file_list_cardinality_estimate) {
return file_list_cardinality_estimate;
}
if (data.file_options.union_by_name) {
// for UNION BY NAME - check if we can get a cardinality estimate from the (already opened) union readers
// a single file opened at bind for its schema keeps the format's own estimate (e.g. explicit_cardinality);
// files opened for their statistics alone (ReadFilesForStatistics after a custom Bind) are counted here
const bool opened_for_statistics =
data.file_options.union_by_name || data.union_readers.size() > 1 || !data.initial_reader;
if (!data.union_readers.empty() && opened_for_statistics &&
data.union_readers.size() == data.file_list->GetTotalFileCount()) {
// check if we can get a cardinality estimate from the (already opened) union readers
bool has_exact_cardinality = true;
idx_t cardinality = 0;
for (auto &union_data : data.union_readers) {
Expand All @@ -1312,7 +1373,15 @@ class MultiFileFunction : public TableFunction {
cardinality += file_cardinality.GetIndex();
}
if (has_exact_cardinality) {
return make_uniq<NodeStatistics>(cardinality);
// the files' totals are the estimate; the maximum is what the format proves the scan reads, as a
// footer's total is not checked against the rows it holds
auto result = make_uniq<NodeStatistics>(cardinality);
auto format_stats = data.interface->GetCardinality(context, data, data.union_readers.size());
if (format_stats && format_stats->has_max_cardinality) {
result->has_max_cardinality = true;
result->max_cardinality = format_stats->max_cardinality;
}
return result;
}
}
// get the file count - for >500 files we allow an estimate
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,9 @@ struct MultiFileOptions {
//! The maximum number of files that are opened to determine the schema - the schemas of the sampled files are
//! combined into one. NumericLimits<idx_t>::Maximum() samples every file
idx_t maximum_sample_files = 1;
//! A scan of at most this many files (0: none) opens all of them at bind for their exact row count and merged
//! column statistics, without changing the schema. Not serialized
idx_t maximum_files_for_stats = 0;
//! Whether the schemas of the sampled files are combined into a union of their columns - files are then allowed
//! to be missing columns of the combined schema, the way they are with union_by_name. This is how the schemas of
//! sampled files are combined unless the reader combines them itself
Expand Down
Loading
Loading