diff --git a/cpp/src/arrow/dataset/CMakeLists.txt b/cpp/src/arrow/dataset/CMakeLists.txt index cfb2c9ba78d..416288486de 100644 --- a/cpp/src/arrow/dataset/CMakeLists.txt +++ b/cpp/src/arrow/dataset/CMakeLists.txt @@ -31,6 +31,7 @@ endif() set(ARROW_DATASET_SRCS dataset.cc dataset_writer.cc + dataset_writer_cleanup.cc discovery.cc file_base.cc file_ipc.cc diff --git a/cpp/src/arrow/dataset/dataset_writer.cc b/cpp/src/arrow/dataset/dataset_writer.cc index f5104efb70b..b536757b927 100644 --- a/cpp/src/arrow/dataset/dataset_writer.cc +++ b/cpp/src/arrow/dataset/dataset_writer.cc @@ -120,6 +120,7 @@ struct DatasetWriterState { const uint64_t max_rows_staged; // Mutex to guard access to the file visitors in the writer options std::mutex visitors_mutex; + DatasetWriteCleanup cleanup; }; Result> OpenWriter( @@ -382,36 +383,17 @@ class DatasetWriterDirectoryQueue return; } init_future_ = Future<>::Make(); - auto create_dir_cb = [this] { - return DeferNotOk(write_options_.filesystem->io_context().executor()->Submit( - [this]() { return write_options_.filesystem->CreateDir(directory_); })); - }; - // We need to notify waiters whether the directory succeeded or failed. - auto notify_waiters_cb = [this] { init_future_.MarkFinished(); }; - auto notify_waiters_on_err_cb = [this](const Status& err) { - // If there is an error the scheduler will abort but that takes some time - // and we don't want to start writing in the meantime so we send an error to the - // file writing queue and return the error. - init_future_.MarkFinished(err); - return err; - }; - std::function()> init_task; - if (write_options_.existing_data_behavior == - ExistingDataBehavior::kDeleteMatchingPartitions) { - init_task = [this, create_dir_cb, notify_waiters_cb, notify_waiters_on_err_cb] { - return write_options_.filesystem - ->DeleteDirContentsAsync(directory_, - /*missing_dir_ok=*/true) - .Then(create_dir_cb) - .Then(notify_waiters_cb, notify_waiters_on_err_cb); - }; - } else { - init_task = [create_dir_cb, notify_waiters_cb, notify_waiters_on_err_cb] { - return create_dir_cb().Then(notify_waiters_cb, notify_waiters_on_err_cb); - }; - } - scheduler_->AddSimpleTask(std::move(init_task), - "DatasetWriter::InitializeDirectory"sv); + scheduler_->AddSimpleTask( + [self = shared_from_this()] { + auto initialized = self->writer_state_->cleanup.Initialize( + self->write_options_, self->directory_, self->prefix_); + initialized.AddCallback( + [ready = self->init_future_](const Status& status) mutable { + ready.MarkFinished(status); + }); + return initialized; + }, + "DatasetWriter::InitializeDirectory"sv); } static Result> Make( diff --git a/cpp/src/arrow/dataset/dataset_writer.h b/cpp/src/arrow/dataset/dataset_writer.h index edb1649b5f1..bce7543d04b 100644 --- a/cpp/src/arrow/dataset/dataset_writer.h +++ b/cpp/src/arrow/dataset/dataset_writer.h @@ -17,7 +17,9 @@ #pragma once +#include #include +#include #include "arrow/dataset/file_base.h" #include "arrow/record_batch.h" @@ -32,6 +34,23 @@ namespace internal { // This lines up with our other defaults in the scanner and execution plan constexpr uint64_t kDefaultDatasetWriterMaxRowsQueued = 8 * 1024 * 1024; +// Prepares partition destinations and shares the filename-partition snapshot. +class DatasetWriteCleanup { + public: + Future<> Initialize(const FileSystemDatasetWriteOptions& options, + const std::string& directory, const std::string& prefix); + + private: + using FilesByPrefix = std::unordered_map; + + Future<> DeleteFilenamePartition(const FileSystemDatasetWriteOptions& options, + const std::string& directory, + const std::string& prefix); + + std::once_flag list_files_; + Future existing_files_; +}; + /// \brief Utility class that manages a set of writers to different paths /// /// Writers may be closed and reopened (and a new file created) based on the dataset diff --git a/cpp/src/arrow/dataset/dataset_writer_cleanup.cc b/cpp/src/arrow/dataset/dataset_writer_cleanup.cc new file mode 100644 index 00000000000..f75d3d586b1 --- /dev/null +++ b/cpp/src/arrow/dataset/dataset_writer_cleanup.cc @@ -0,0 +1,99 @@ +// 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. + +#include "arrow/dataset/dataset_writer.h" + +#include +#include + +#include "arrow/compute/expression.h" +#include "arrow/dataset/partition.h" +#include "arrow/util/async_generator.h" + +namespace arrow::dataset::internal { + +Future<> DatasetWriteCleanup::Initialize(const FileSystemDatasetWriteOptions& options, + const std::string& directory, + const std::string& prefix) { + const auto& filesystem = options.filesystem; + auto create_directory = [filesystem, directory] { + return DeferNotOk(filesystem->io_context().executor()->Submit( + [filesystem, directory] { return filesystem->CreateDir(directory); })); + }; + if (options.existing_data_behavior != ExistingDataBehavior::kDeleteMatchingPartitions) { + return create_directory(); + } + if (directory != options.base_dir || + dynamic_cast(options.partitioning.get()) == nullptr) { + return filesystem->DeleteDirContentsAsync(directory, /*missing_dir_ok=*/true) + .Then(create_directory); + } + return DeleteFilenamePartition(options, directory, prefix).Then(create_directory); +} + +Future<> DatasetWriteCleanup::DeleteFilenamePartition( + const FileSystemDatasetWriteOptions& options, const std::string& directory, + const std::string& prefix) { + const auto& filesystem = options.filesystem; + std::call_once(list_files_, [&] { + // Filename partitions share a directory. Read the old file list before + // releasing any partition to write new files into it. + fs::FileSelector selector; + selector.base_dir = directory; + selector.allow_not_found = true; + auto files = std::make_shared(); + auto collect = [files, partitioning = + options.partitioning](const fs::FileInfoVector& entries) { + for (const auto& info : entries) { + if (info.type() != fs::FileType::File) continue; + auto expression = partitioning->Parse(info.path()); + if (!expression.ok() || (partitioning->schema()->num_fields() > 0 && + *expression == compute::literal(true))) { + continue; + } + auto path = partitioning->Format(*expression); + if (path.ok()) { + (*files)[path->filename].push_back(info); + } + } + return Status::OK(); + }; + existing_files_ = VisitAsyncGenerator(filesystem->GetFileInfoGenerator(selector), + std::move(collect)) + .Then([files] { return std::move(*files); }); + }); + + return existing_files_.Then( + [filesystem, format = options.format(), prefix](const FilesByPrefix& files) { + auto matching = files.find(prefix); + if (matching == files.end()) { + return Future<>::MakeFinished(); + } + return DeferNotOk(filesystem->io_context().executor()->Submit( + [filesystem, format, entries = matching->second] { + std::vector paths; + for (const auto& info : entries) { + ARROW_ASSIGN_OR_RAISE(bool supported, + format->IsSupported(FileSource(info, filesystem))); + if (supported) paths.push_back(info.path()); + } + return filesystem->DeleteFiles(paths); + })); + }); +} + +} // namespace arrow::dataset::internal diff --git a/cpp/src/arrow/dataset/type_fwd.h b/cpp/src/arrow/dataset/type_fwd.h index d58781e038d..c0558662831 100644 --- a/cpp/src/arrow/dataset/type_fwd.h +++ b/cpp/src/arrow/dataset/type_fwd.h @@ -56,7 +56,9 @@ class WriteNodeOptions; /// \brief Controls what happens if files exist in an output directory during a dataset /// write enum class ExistingDataBehavior : int8_t { - /// Deletes all files in a directory the first time that directory is encountered + /// Replaces each written partition. For directory partitioning, delete the + /// partition directory contents. For filename partitioning, delete files of + /// the selected format whose parsed keys match the partition. kDeleteMatchingPartitions, /// Ignores existing files, overwriting any that happen to have the same name as an /// output file diff --git a/cpp/src/arrow/dataset/write_node_test.cc b/cpp/src/arrow/dataset/write_node_test.cc index f420bd2e6ca..dee06ad9d7d 100644 --- a/cpp/src/arrow/dataset/write_node_test.cc +++ b/cpp/src/arrow/dataset/write_node_test.cc @@ -22,12 +22,16 @@ #include "arrow/acero/exec_plan.h" #include "arrow/acero/options.h" +#include "arrow/compute/api_vector.h" +#include "arrow/dataset/discovery.h" #include "arrow/dataset/file_base.h" #include "arrow/dataset/file_ipc.h" #include "arrow/dataset/partition.h" #include "arrow/dataset/plan.h" #include "arrow/filesystem/filesystem.h" +#include "arrow/filesystem/localfs.h" #include "arrow/filesystem/mockfs.h" +#include "arrow/filesystem/path_util.h" #include "arrow/io/interfaces.h" #include "arrow/ipc/reader.h" #include "arrow/testing/generator.h" @@ -35,8 +39,14 @@ #include "arrow/testing/matchers.h" #include "arrow/table.h" +#include "arrow/util/config.h" +#include "arrow/util/io_util.h" #include "arrow/util/key_value_metadata.h" +#ifdef ARROW_PARQUET +# include "arrow/dataset/file_parquet.h" +#endif + namespace arrow { namespace dataset { @@ -55,10 +65,136 @@ class SimpleWriteNodeTest : public ::testing::Test { fs_write_options_.partitioning = dataset::Partitioning::Default(); } + static Status WriteTable(const FileSystemDatasetWriteOptions& options, + const std::shared_ptr& table) { + auto dataset = std::make_shared(table); + ARROW_ASSIGN_OR_RAISE(auto builder, dataset->NewScan()); + ARROW_ASSIGN_OR_RAISE(auto scanner, builder->Finish()); + return FileSystemDataset::Write(options, scanner); + } + std::shared_ptr mock_fs_; dataset::FileSystemDatasetWriteOptions fs_write_options_; }; +#ifdef ARROW_PARQUET +TEST_F(SimpleWriteNodeTest, DeleteMatchingPartitions) { + const auto data_schema = schema({field("year", int32()), field("value", int32())}); + const auto partition_schema = schema({data_schema->field(0)}); + auto original = TableFromJSON(data_schema, {R"([[2019, -1], [20190, -2]])"}); + auto updates = TableFromJSON(data_schema, {R"([[2019, 1], [2020, 2], [2021, 3]])", + R"([[2019, 4], [2021, 5], [2022, 6]])"}); + auto expected = TableFromJSON(data_schema, {R"([ + [20190, -2], [2019, 1], [2020, 2], [2021, 3], [2019, 4], [2021, 5], + [2022, 6] + ])"}); + auto filesystem = std::make_shared(); + auto format = std::make_shared(); + + for (const auto& partitioning : std::vector>{ + std::make_shared(partition_schema), + std::make_shared(partition_schema)}) { + SCOPED_TRACE(partitioning->type_name()); + ASSERT_OK_AND_ASSIGN(auto tempdir, + ::arrow::internal::TemporaryDir::Make("delete-matching-")); + ASSERT_OK_AND_ASSIGN(auto path, tempdir->path().Join("data")); + auto options = fs_write_options_; + options.filesystem = filesystem; + options.base_dir = path.ToString(); + options.file_write_options = format->DefaultWriteOptions(); + options.partitioning = partitioning; + options.basename_template = "old_{i}.parquet"; + options.existing_data_behavior = ExistingDataBehavior::kDeleteMatchingPartitions; + ASSERT_OK(WriteTable(options, original->Slice(0, 1))); + options.existing_data_behavior = ExistingDataBehavior::kOverwriteOrIgnore; + ASSERT_OK(WriteTable(options, original->Slice(1, 1))); + + const bool filenames = partitioning->type_name() == "filename"; + const auto join = [&](std::string_view part) { + return fs::internal::ConcatAbstractPath(options.base_dir, part); + }; + const auto old_match = join(filenames ? "2019_old_0.parquet" : "2019/old_0.parquet"); + const auto alias = join("02019_older.parquet"); + const auto notes = join("2019_notes.txt"); + const auto unpartitioned = join(".unpartitioned.parquet"); + if (filenames) { + ASSERT_OK(filesystem->Move(old_match, alias)); + ASSERT_OK(filesystem->CopyFile(alias, unpartitioned)); + ASSERT_OK_AND_ASSIGN(auto stream, filesystem->OpenOutputStream(notes)); + ASSERT_OK(stream->Write("Notes independent of this Parquet dataset")); + ASSERT_OK(stream->Close()); + } + + options.basename_template = "part{i}.parquet"; + options.existing_data_behavior = ExistingDataBehavior::kDeleteMatchingPartitions; + options.max_rows_per_file = options.max_rows_per_group = 1; + ASSERT_OK(WriteTable(options, updates)); + + ASSERT_OK_AND_ASSIGN(auto stale, + filesystem->GetFileInfo(filenames ? alias : old_match)); + EXPECT_EQ(stale.type(), fs::FileType::NotFound); + if (filenames) { + ASSERT_OK_AND_ASSIGN(auto info, filesystem->GetFileInfo(notes)); + EXPECT_EQ(info.type(), fs::FileType::File); + ASSERT_OK_AND_ASSIGN(auto unpartitioned_info, + filesystem->GetFileInfo(unpartitioned)); + EXPECT_EQ(unpartitioned_info.type(), fs::FileType::File); + } + + fs::FileSelector selector; + selector.base_dir = options.base_dir; + selector.recursive = true; + FileSystemFactoryOptions factory_options; + factory_options.partitioning = partitioning; + factory_options.partition_base_dir = options.base_dir; + factory_options.exclude_invalid_files = true; + ASSERT_OK_AND_ASSIGN( + auto factory, + FileSystemDatasetFactory::Make(filesystem, selector, format, factory_options)); + ASSERT_OK_AND_ASSIGN(auto dataset, factory->Finish()); + ASSERT_OK_AND_ASSIGN(auto builder, dataset->NewScan()); + ASSERT_OK(builder->Project({"year", "value"})); + ASSERT_OK_AND_ASSIGN(auto scanner, builder->Finish()); + ASSERT_OK_AND_ASSIGN(auto readback, scanner->ToTable()); + ASSERT_OK_AND_ASSIGN( + auto indices, compute::SortIndices( + readback, compute::SortOptions({compute::SortKey("value")}))); + ASSERT_OK_AND_ASSIGN(auto sorted, compute::Take(readback, indices)); + AssertTablesEqual(*expected, *sorted.table(), /*same_chunk_layout=*/false); + } +} + +TEST_F(SimpleWriteNodeTest, DeleteMatchingEmptyFilenamePartition) { + auto data_schema = schema({field("value", int32())}); + auto old = TableFromJSON(data_schema, {R"([[-1]])"}); + auto updated = TableFromJSON(data_schema, {R"([[1], [2]])"}); + auto format = std::make_shared(); + auto partitioning = std::make_shared(schema({})); + + auto options = fs_write_options_; + options.partitioning = partitioning; + options.file_write_options = format->DefaultWriteOptions(); + options.existing_data_behavior = ExistingDataBehavior::kDeleteMatchingPartitions; + options.basename_template = "old{i}.parquet"; + ASSERT_OK(WriteTable(options, old)); + options.basename_template = "updated{i}.parquet"; + ASSERT_OK(WriteTable(options, updated)); + + fs::FileSelector selector; + selector.base_dir = options.base_dir; + FileSystemFactoryOptions factory_options; + factory_options.partitioning = partitioning; + factory_options.selector_ignore_prefixes.clear(); + ASSERT_OK_AND_ASSIGN(auto factory, FileSystemDatasetFactory::Make( + mock_fs_, selector, format, factory_options)); + ASSERT_OK_AND_ASSIGN(auto dataset, factory->Finish()); + ASSERT_OK_AND_ASSIGN(auto builder, dataset->NewScan()); + ASSERT_OK_AND_ASSIGN(auto scanner, builder->Finish()); + ASSERT_OK_AND_ASSIGN(auto readback, scanner->ToTable()); + AssertTablesEqual(*updated, *readback, /*same_chunk_layout=*/false); +} +#endif + TEST_F(SimpleWriteNodeTest, CustomNullability) { // Create an input table with a nullable and a non-nullable type ExecBatch batch = gen::Gen({gen::Step()})->FailOnError()->ExecBatch(/*num_rows=*/1); diff --git a/python/pyarrow/dataset.py b/python/pyarrow/dataset.py index f696d5f03ba..68d7b46c807 100644 --- a/python/pyarrow/dataset.py +++ b/python/pyarrow/dataset.py @@ -950,10 +950,9 @@ def file_visitor(written_file): with a unique basename_template for each write, will allow for an append workflow. - 'delete_matching' is useful when you are writing a partitioned - dataset. The first time each partition directory is encountered - the entire directory will be deleted. This allows you to overwrite - old partitions completely. + 'delete_matching' replaces each written partition. It clears + partition directories, or deletes matching files of the selected + format for filename partitioning. Use a dedicated dataset directory. create_dir : bool, default True If False, directories will not be created. This can be useful for filesystems that do not require directories.