From ab2ab46400f7674f36366fad598c7fdbc1b8a514 Mon Sep 17 00:00:00 2001 From: David Greiss Date: Sun, 2 Jul 2023 17:29:14 -0400 Subject: [PATCH 01/17] Add write_csv_dataset --- r/R/dataset-write.R | 39 ++++++++++++++++++++ r/tests/testthat/test-dataset-write.R | 51 +++++++++++++++++++++++++++ 2 files changed, 90 insertions(+) diff --git a/r/R/dataset-write.R b/r/R/dataset-write.R index f971c0e9cd6e..a6ec3efa751b 100644 --- a/r/R/dataset-write.R +++ b/r/R/dataset-write.R @@ -209,6 +209,45 @@ write_dataset <- function(dataset, ) } +#' Write a dataset into partitioned csv files. + +#' A wrapper around [write_dataset] to allow for easy switching between functions for writing datasets. + +#' @seealso [write_dataset()] +#' @export +write_csv_dataset <- function(dataset, + path, + partitioning = dplyr::group_vars(dataset), + basename_template = "part-{i}.csv", + hive_style = TRUE, + existing_data_behavior = c("overwrite", "error", "delete_matching"), + max_partitions = 1024L, + max_open_files = 900L, + max_rows_per_file = 0L, + min_rows_per_group = 0L, + max_rows_per_group = bitwShiftL(1, 20), + ...) { + if (!missing(max_rows_per_file) && missing(max_rows_per_group) && max_rows_per_group > max_rows_per_file) { + max_rows_per_group <- max_rows_per_file + } + + write_dataset( + dataset = dataset, + path = path, + format = "csv", + partitioning = partitioning, + basename_template = basename_template, + hive_style = hive_style, + existing_data_behavior = existing_data_behavior, + max_partitions = max_partitions, + max_open_files = max_open_files, + max_rows_per_file = max_rows_per_file, + min_rows_per_group = min_rows_per_group, + max_rows_per_group = max_rows_per_group, + ... + ) +} + validate_positive_int_value <- function(value, msg) { if (!is_integerish(value, n = 1) || is.na(value) || value < 0) { abort(paste(substitute(value), "must be a positive, non-missing integer")) diff --git a/r/tests/testthat/test-dataset-write.R b/r/tests/testthat/test-dataset-write.R index 8553dafd80f9..b8d2afe868a6 100644 --- a/r/tests/testthat/test-dataset-write.R +++ b/r/tests/testthat/test-dataset-write.R @@ -812,3 +812,54 @@ test_that("write_dataset() errors on data.frame with NULL names", { names(df) <- NULL expect_error(write_dataset(df, tempfile()), "Input data frame columns must be named") }) + +test_that("Writing a dataset using write_csv_dataset wrapper", { + df <- tibble( + int = 1:10, + dbl = as.numeric(1:10), + lgl = rep(c(TRUE, FALSE, NA, TRUE, FALSE), 2), + chr = letters[1:10], + ) + + dst_dir <- make_temp_dir() + write_csv_dataset(df, dst_dir) + expect_true(dir.exists(dst_dir)) + new_ds <- open_dataset(dst_dir, format = "csv") + expect_equal(new_ds %>% collect(), df) + + dst_dir <- make_temp_dir() + write_csv_dataset(df, dst_dir, include_header = FALSE) + expect_true(dir.exists(dst_dir)) + new_ds <- open_dataset(dst_dir, + format = "csv", + column_names = c("int", "dbl", "lgl", "chr") + ) + expect_equal(new_ds %>% collect(), df) +}) + +test_that("Writing a csv dataset: `basename_template` default behavier", { + ds <- open_dataset(csv_dir, partitioning = "part", format = "csv") + + dst_dir <- make_temp_dir() + write_csv_dataset(ds, dst_dir, max_rows_per_file = 5L) + expect_identical( + dir(dst_dir, full.names = FALSE, recursive = TRUE), + paste0("part-", 0:3, ".csv") + ) +}) + +test_that("max_rows_per_group is adjusted if at odds with max_rows_per_file in write_csv_dataset()", { + skip_if_not_available("parquet") + df <- tibble::tibble( + int = 1:10, + dbl = as.numeric(1:10), + lgl = rep(c(TRUE, FALSE, NA, TRUE, FALSE), 2), + chr = letters[1:10], + ) + dst_dir <- make_temp_dir() + + # max_rows_per_group unset adjust silently + expect_silent( + write_csv_dataset(df, dst_dir, max_rows_per_file = 5) + ) +}) From 7e94d3ec8b181ceb386cfcd853c1e92be62775af Mon Sep 17 00:00:00 2001 From: David Greiss Date: Sun, 2 Jul 2023 18:03:32 -0400 Subject: [PATCH 02/17] Add docs --- r/_pkgdown.yml | 1 + r/man/write_csv_dataset.Rd | 27 +++++++++++++++++++++++++++ 2 files changed, 28 insertions(+) create mode 100644 r/man/write_csv_dataset.Rd diff --git a/r/_pkgdown.yml b/r/_pkgdown.yml index 26a77199b560..3369473c172f 100644 --- a/r/_pkgdown.yml +++ b/r/_pkgdown.yml @@ -145,6 +145,7 @@ reference: - open_csv_dataset - open_tsv_dataset - write_dataset + - write_csv_dataset - dataset_factory - hive_partition - Dataset diff --git a/r/man/write_csv_dataset.Rd b/r/man/write_csv_dataset.Rd new file mode 100644 index 000000000000..5e93c99e931a --- /dev/null +++ b/r/man/write_csv_dataset.Rd @@ -0,0 +1,27 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/dataset-write.R +\name{write_csv_dataset} +\alias{write_csv_dataset} +\title{Write a dataset into partitioned csv files.} +\usage{ +write_csv_dataset( + dataset, + path, + partitioning = dplyr::group_vars(dataset), + basename_template = "part-{i}.csv", + hive_style = TRUE, + existing_data_behavior = c("overwrite", "error", "delete_matching"), + max_partitions = 1024L, + max_open_files = 900L, + max_rows_per_file = 0L, + min_rows_per_group = 0L, + max_rows_per_group = bitwShiftL(1, 20), + ... +) +} +\description{ +A wrapper around \link{write_dataset} to allow for easy switching between functions for writing datasets. +} +\seealso{ +\code{\link[=write_dataset]{write_dataset()}} +} From 39ca7c12e29bf1827d5375882eed64ae4d421fcb Mon Sep 17 00:00:00 2001 From: David Greiss Date: Tue, 4 Jul 2023 00:27:26 -0400 Subject: [PATCH 03/17] add write_delim and write_tsv wrappers --- r/NAMESPACE | 3 + r/R/csv.R | 26 +++- r/R/dataset-format.R | 7 +- r/R/dataset-write.R | 162 +++++++++++++++++++++-- r/man/write_csv_dataset.Rd | 27 ---- r/man/write_dataset.Rd | 2 +- r/man/write_delim_dataset.Rd | 129 ++++++++++++++++++ r/src/csv.cpp | 4 +- r/tests/testthat/_snaps/dataset-write.md | 2 +- r/tests/testthat/test-dataset-write.R | 85 ++++++++++-- 10 files changed, 391 insertions(+), 56 deletions(-) delete mode 100644 r/man/write_csv_dataset.Rd create mode 100644 r/man/write_delim_dataset.Rd diff --git a/r/NAMESPACE b/r/NAMESPACE index 2bf1a863a2ef..a943d9f8f8b1 100644 --- a/r/NAMESPACE +++ b/r/NAMESPACE @@ -398,12 +398,15 @@ export(value_counts) export(vctrs_extension_array) export(vctrs_extension_type) export(write_csv_arrow) +export(write_csv_dataset) export(write_dataset) +export(write_delim_dataset) export(write_feather) export(write_ipc_file) export(write_ipc_stream) export(write_parquet) export(write_to_raw) +export(write_tsv_dataset) importFrom(R6,R6Class) importFrom(assertthat,assert_that) importFrom(assertthat,is.string) diff --git a/r/R/csv.R b/r/R/csv.R index 6af46acb258b..b531a160e357 100644 --- a/r/R/csv.R +++ b/r/R/csv.R @@ -512,30 +512,46 @@ CsvReadOptions$create <- function(use_threads = option_use_threads(), readr_to_csv_write_options <- function(include_header = TRUE, batch_size = 1024L, - na = "") { + delim = ",", + na = "", + eol = "\n") { CsvWriteOptions$create( include_header = include_header, batch_size = batch_size, - null_string = na + delimiter = delim, + null_string = na, + eol = eol ) } #' @rdname CsvReadOptions #' @export CsvWriteOptions <- R6Class("CsvWriteOptions", inherit = ArrowObject) -CsvWriteOptions$create <- function(include_header = TRUE, batch_size = 1024L, null_string = "") { - assert_that(is_integerish(batch_size, n = 1, finite = TRUE), batch_size > 0) +CsvWriteOptions$create <- function(include_header = TRUE, + batch_size = 1024L, + delimiter = ",", + null_string = "", + eol = "\n") { assert_that(is.logical(include_header)) + + assert_that(is_integerish(batch_size, n = 1, finite = TRUE), batch_size > 0) + + assert_that(is.character(delimiter)) + assert_that(is.character(null_string)) assert_that(!is.na(null_string)) assert_that(length(null_string) == 1) assert_that(!grepl('"', null_string), msg = "na argument must not contain quote characters.") + assert_that(is.character(eol)) + csv___WriteOptions__initialize( list( include_header = include_header, batch_size = as.integer(batch_size), - null_string = as.character(null_string) + delimiter = delimiter, + null_string = as.character(null_string), + eol = eol ) ) } diff --git a/r/R/dataset-format.R b/r/R/dataset-format.R index 8798e0248e0f..f48d8cfa0cba 100644 --- a/r/R/dataset-format.R +++ b/r/R/dataset-format.R @@ -76,9 +76,10 @@ FileFormat <- R6Class("FileFormat", ) FileFormat$create <- function(format, schema = NULL, ...) { opt_names <- names(list(...)) - if (format %in% c("csv", "text") || any(opt_names %in% c("delim", "delimiter"))) { + if (format %in% c("csv", "text", "txt") || any(opt_names %in% c("delim", "delimiter"))) { CsvFileFormat$create(schema = schema, ...) } else if (format == "tsv") { + # This delimiter argument is ignored. CsvFileFormat$create(delimiter = "\t", schema = schema, ...) } else if (format == "parquet") { ParquetFileFormat$create(...) @@ -623,7 +624,7 @@ FileWriteOptions <- R6Class("FileWriteOptions", "codec", "null_fallback" ) - } else if (format == "csv") { + } else if (format %in% c("csv", "tsv", "txt", "text")) { supported_args <- c( names(formals(CsvWriteOptions$create)), names(formals(readr_to_csv_write_options)) @@ -679,7 +680,7 @@ FileWriteOptions <- R6Class("FileWriteOptions", get_ipc_metadata_version(args$metadata_version) ) } - } else if (self$type == "csv") { + } else if (self$type %in% c("csv", "tsv", "txt", "text")) { arrow_opts <- names(formals(CsvWriteOptions$create)) readr_opts <- names(formals(readr_to_csv_write_options)) readr_only_opts <- setdiff(readr_opts, arrow_opts) diff --git a/r/R/dataset-write.R b/r/R/dataset-write.R index a6ec3efa751b..5c83082ca978 100644 --- a/r/R/dataset-write.R +++ b/r/R/dataset-write.R @@ -122,7 +122,7 @@ #' @export write_dataset <- function(dataset, path, - format = c("parquet", "feather", "arrow", "ipc", "csv"), + format = c("parquet", "feather", "arrow", "ipc", "csv", "tsv", "txt", "text"), partitioning = dplyr::group_vars(dataset), basename_template = paste0("part-{i}.", as.character(format)), hive_style = TRUE, @@ -178,12 +178,32 @@ write_dataset <- function(dataset, } path_and_fs <- get_path_and_filesystem(path) + + dots <- list(...) + if (format %in% c("csv", "tsv") && any(c("delimiter", "delim") %in% names(dots))) { + stop("Do not set a delimiter for csv or tsv formats.") + } + + if (format %in% c("txt", "text") && !any(c("delimiter", "delim") %in% names(dots))) { + stop("A delimiter must be given for a txt format.") + } + output_schema <- final_node$schema - options <- FileWriteOptions$create( - format, - column_names = names(output_schema), - ... - ) + # This is a workaround because CsvFileFormat$create defaults the delimiter to "," + if (format == "tsv") { + options <- FileWriteOptions$create( + format, + column_names = names(output_schema), + delimiter = "\t", + ... + ) + } else { + options <- FileWriteOptions$create( + format, + column_names = names(output_schema), + ... + ) + } # TODO(ARROW-16200): expose FileSystemDatasetWriteOptions in R # and encapsulate this logic better @@ -209,11 +229,100 @@ write_dataset <- function(dataset, ) } -#' Write a dataset into partitioned csv files. +#' Write a dataset into partitioned flat files. +#' +#' The `write_*_dataset()` are a family of wrappers around [write_dataset] to allow for easy switching +#' between functions for writing datasets. +#' +#' @param dataset [Dataset], [RecordBatch], [Table], `arrow_dplyr_query`, or +#' `data.frame`. If an `arrow_dplyr_query`, the query will be evaluated and +#' the result will be written. This means that you can `select()`, `filter()`, `mutate()`, +#' etc. to transform the data before it is written if you need to. +#' @param path string path, URI, or `SubTreeFileSystem` referencing a directory +#' to write to (directory will be created if it does not exist) +#' @param partitioning `Partitioning` or a character vector of columns to +#' use as partition keys (to be written as path segments). Default is to +#' use the current `group_by()` columns. +#' @param basename_template string template for the names of files to be written. +#' Must contain `"{i}"`, which will be replaced with an autoincremented +#' integer to generate basenames of datafiles. For example, `"part-{i}.csv"` +#' will yield `"part-0.csv", ...`. +#' If not specified, it defaults to `"part-{i}.csv"`. +#' @param hive_style logical: write partition segments as Hive-style +#' (`key1=value1/key2=value2/file.ext`) or as just bare values. Default is `TRUE`. +#' @param existing_data_behavior The behavior to use when there is already data +#' in the destination directory. Must be one of "overwrite", "error", or +#' "delete_matching". +#' - "overwrite" (the default) then any new files created will overwrite +#' existing files +#' - "error" then the operation will fail if the destination directory is not +#' empty +#' - "delete_matching" then the writer will delete any existing partitions +#' if data is going to be written to those partitions and will leave alone +#' partitions which data is not written to. +#' @param max_partitions maximum number of partitions any batch may be +#' written into. Default is 1024L. +#' @param max_open_files maximum number of files that can be left opened +#' during a write operation. If greater than 0 then this will limit the +#' maximum number of files that can be left open. If an attempt is made to open +#' too many files then the least recently used file will be closed. +#' If this setting is set too low you may end up fragmenting your data +#' into many small files. The default is 900 which also allows some # of files to be +#' open by the scanner before hitting the default Linux limit of 1024. +#' @param max_rows_per_file maximum number of rows per file. +#' If greater than 0 then this will limit how many rows are placed in any single file. +#' Default is 0L. +#' @param min_rows_per_group write the row groups to the disk when this number of +#' rows have accumulated. Default is 0L. +#' @param max_rows_per_group maximum rows allowed in a single +#' group and when this number of rows is exceeded, it is split and the next set +#' of rows is written to the next group. This value must be set such that it is +#' greater than `min_rows_per_group`. Default is 1024 * 1024. +#' @param delimiter Delimiter used to separate values. Defaults to `","` for `write_delim_dataset()` and +#' `write_csv_dataset()`, and `"\t` for `write_tsv_dataset()`. Cannot be changed for `write_csv_dataset()` +#' and `write_tsv_dataset()`. +#' @param ... additional format-specific arguments. For available CSV +#' options, see [CsvWriteOptions]. +#' @return The input `dataset`, invisibly +#' +#' @seealso [write_dataset()] +#' @export +write_delim_dataset <- function(dataset, + path, + partitioning = dplyr::group_vars(dataset), + basename_template = "part-{i}.txt", + hive_style = TRUE, + existing_data_behavior = c("overwrite", "error", "delete_matching"), + max_partitions = 1024L, + max_open_files = 900L, + max_rows_per_file = 0L, + min_rows_per_group = 0L, + max_rows_per_group = bitwShiftL(1, 20), + delimiter = ",", + ...) { + if (!missing(max_rows_per_file) && missing(max_rows_per_group) && max_rows_per_group > max_rows_per_file) { + max_rows_per_group <- max_rows_per_file + } -#' A wrapper around [write_dataset] to allow for easy switching between functions for writing datasets. + write_dataset( + dataset = dataset, + path = path, + format = "txt", + partitioning = partitioning, + basename_template = basename_template, + hive_style = hive_style, + existing_data_behavior = existing_data_behavior, + max_partitions = max_partitions, + max_open_files = max_open_files, + max_rows_per_file = max_rows_per_file, + min_rows_per_group = min_rows_per_group, + max_rows_per_group = max_rows_per_group, + delimiter = delimiter, + ... + ) +} -#' @seealso [write_dataset()] +#' @rdname write_delim_dataset #' @export write_csv_dataset <- function(dataset, path, @@ -248,6 +357,41 @@ write_csv_dataset <- function(dataset, ) } +#' @rdname write_delim_dataset +#' @export +write_tsv_dataset <- function(dataset, + path, + partitioning = dplyr::group_vars(dataset), + basename_template = "part-{i}.tsv", + hive_style = TRUE, + existing_data_behavior = c("overwrite", "error", "delete_matching"), + max_partitions = 1024L, + max_open_files = 900L, + max_rows_per_file = 0L, + min_rows_per_group = 0L, + max_rows_per_group = bitwShiftL(1, 20), + ...) { + if (!missing(max_rows_per_file) && missing(max_rows_per_group) && max_rows_per_group > max_rows_per_file) { + max_rows_per_group <- max_rows_per_file + } + + write_dataset( + dataset = dataset, + path = path, + format = "tsv", + partitioning = partitioning, + basename_template = basename_template, + hive_style = hive_style, + existing_data_behavior = existing_data_behavior, + max_partitions = max_partitions, + max_open_files = max_open_files, + max_rows_per_file = max_rows_per_file, + min_rows_per_group = min_rows_per_group, + max_rows_per_group = max_rows_per_group, + ... + ) +} + validate_positive_int_value <- function(value, msg) { if (!is_integerish(value, n = 1) || is.na(value) || value < 0) { abort(paste(substitute(value), "must be a positive, non-missing integer")) diff --git a/r/man/write_csv_dataset.Rd b/r/man/write_csv_dataset.Rd deleted file mode 100644 index 5e93c99e931a..000000000000 --- a/r/man/write_csv_dataset.Rd +++ /dev/null @@ -1,27 +0,0 @@ -% Generated by roxygen2: do not edit by hand -% Please edit documentation in R/dataset-write.R -\name{write_csv_dataset} -\alias{write_csv_dataset} -\title{Write a dataset into partitioned csv files.} -\usage{ -write_csv_dataset( - dataset, - path, - partitioning = dplyr::group_vars(dataset), - basename_template = "part-{i}.csv", - hive_style = TRUE, - existing_data_behavior = c("overwrite", "error", "delete_matching"), - max_partitions = 1024L, - max_open_files = 900L, - max_rows_per_file = 0L, - min_rows_per_group = 0L, - max_rows_per_group = bitwShiftL(1, 20), - ... -) -} -\description{ -A wrapper around \link{write_dataset} to allow for easy switching between functions for writing datasets. -} -\seealso{ -\code{\link[=write_dataset]{write_dataset()}} -} diff --git a/r/man/write_dataset.Rd b/r/man/write_dataset.Rd index 1bc940697cc4..34cffefbce5d 100644 --- a/r/man/write_dataset.Rd +++ b/r/man/write_dataset.Rd @@ -7,7 +7,7 @@ write_dataset( dataset, path, - format = c("parquet", "feather", "arrow", "ipc", "csv"), + format = c("parquet", "feather", "arrow", "ipc", "csv", "tsv", "txt", "text"), partitioning = dplyr::group_vars(dataset), basename_template = paste0("part-{i}.", as.character(format)), hive_style = TRUE, diff --git a/r/man/write_delim_dataset.Rd b/r/man/write_delim_dataset.Rd new file mode 100644 index 000000000000..7430ade97d4c --- /dev/null +++ b/r/man/write_delim_dataset.Rd @@ -0,0 +1,129 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/dataset-write.R +\name{write_delim_dataset} +\alias{write_delim_dataset} +\alias{write_csv_dataset} +\alias{write_tsv_dataset} +\title{Write a dataset into partitioned flat files.} +\usage{ +write_delim_dataset( + dataset, + path, + partitioning = dplyr::group_vars(dataset), + basename_template = "part-{i}.txt", + hive_style = TRUE, + existing_data_behavior = c("overwrite", "error", "delete_matching"), + max_partitions = 1024L, + max_open_files = 900L, + max_rows_per_file = 0L, + min_rows_per_group = 0L, + max_rows_per_group = bitwShiftL(1, 20), + delimiter = ",", + ... +) + +write_csv_dataset( + dataset, + path, + partitioning = dplyr::group_vars(dataset), + basename_template = "part-{i}.csv", + hive_style = TRUE, + existing_data_behavior = c("overwrite", "error", "delete_matching"), + max_partitions = 1024L, + max_open_files = 900L, + max_rows_per_file = 0L, + min_rows_per_group = 0L, + max_rows_per_group = bitwShiftL(1, 20), + ... +) + +write_tsv_dataset( + dataset, + path, + partitioning = dplyr::group_vars(dataset), + basename_template = "part-{i}.tsv", + hive_style = TRUE, + existing_data_behavior = c("overwrite", "error", "delete_matching"), + max_partitions = 1024L, + max_open_files = 900L, + max_rows_per_file = 0L, + min_rows_per_group = 0L, + max_rows_per_group = bitwShiftL(1, 20), + ... +) +} +\arguments{ +\item{dataset}{\link{Dataset}, \link{RecordBatch}, \link{Table}, \code{arrow_dplyr_query}, or +\code{data.frame}. If an \code{arrow_dplyr_query}, the query will be evaluated and +the result will be written. This means that you can \code{select()}, \code{filter()}, \code{mutate()}, +etc. to transform the data before it is written if you need to.} + +\item{path}{string path, URI, or \code{SubTreeFileSystem} referencing a directory +to write to (directory will be created if it does not exist)} + +\item{partitioning}{\code{Partitioning} or a character vector of columns to +use as partition keys (to be written as path segments). Default is to +use the current \code{group_by()} columns.} + +\item{basename_template}{string template for the names of files to be written. +Must contain \code{"{i}"}, which will be replaced with an autoincremented +integer to generate basenames of datafiles. For example, \code{"part-{i}.csv"} +will yield \verb{"part-0.csv", ...}. +If not specified, it defaults to \code{"part-{i}.csv"}.} + +\item{hive_style}{logical: write partition segments as Hive-style +(\code{key1=value1/key2=value2/file.ext}) or as just bare values. Default is \code{TRUE}.} + +\item{existing_data_behavior}{The behavior to use when there is already data +in the destination directory. Must be one of "overwrite", "error", or +"delete_matching". +\itemize{ +\item "overwrite" (the default) then any new files created will overwrite +existing files +\item "error" then the operation will fail if the destination directory is not +empty +\item "delete_matching" then the writer will delete any existing partitions +if data is going to be written to those partitions and will leave alone +partitions which data is not written to. +}} + +\item{max_partitions}{maximum number of partitions any batch may be +written into. Default is 1024L.} + +\item{max_open_files}{maximum number of files that can be left opened +during a write operation. If greater than 0 then this will limit the +maximum number of files that can be left open. If an attempt is made to open +too many files then the least recently used file will be closed. +If this setting is set too low you may end up fragmenting your data +into many small files. The default is 900 which also allows some # of files to be +open by the scanner before hitting the default Linux limit of 1024.} + +\item{max_rows_per_file}{maximum number of rows per file. +If greater than 0 then this will limit how many rows are placed in any single file. +Default is 0L.} + +\item{min_rows_per_group}{write the row groups to the disk when this number of +rows have accumulated. Default is 0L.} + +\item{max_rows_per_group}{maximum rows allowed in a single +group and when this number of rows is exceeded, it is split and the next set +of rows is written to the next group. This value must be set such that it is +greater than \code{min_rows_per_group}. Default is 1024 * 1024.} + +\item{delimiter}{Delimiter used to separate values. Defaults to \code{","} for \code{write_delim_dataset()} and +\code{write_csv_dataset()}, and \verb{"\\t} for \code{write_tsv_dataset()}. Cannot be changed for \code{write_csv_dataset()} +and \code{write_tsv_dataset()}.} + +\item{...}{additional format-specific arguments. For available CSV +options, see \link{CsvWriteOptions}.} +} +\value{ +The input \code{dataset}, invisibly +} +\description{ +The \verb{write_*_dataset()} are a family of wrappers around \link{write_dataset} to allow for easy switching +between functions for writing datasets. +} +\seealso{ +\code{\link[=write_dataset]{write_dataset()}} +} diff --git a/r/src/csv.cpp b/r/src/csv.cpp index d04caf5c1fd7..a0f534e1587e 100644 --- a/r/src/csv.cpp +++ b/r/src/csv.cpp @@ -31,8 +31,10 @@ std::shared_ptr csv___WriteOptions__initialize( std::make_shared(arrow::csv::WriteOptions::Defaults()); res->include_header = cpp11::as_cpp(options["include_header"]); res->batch_size = cpp11::as_cpp(options["batch_size"]); - res->io_context = MainRThread::GetInstance().CancellableIOContext(); + res->delimiter = cpp11::as_cpp(options["delimiter"]); res->null_string = cpp11::as_cpp(options["null_string"]); + res->io_context = MainRThread::GetInstance().CancellableIOContext(); + res->eol = cpp11::as_cpp(options["eol"]); return res; } diff --git a/r/tests/testthat/_snaps/dataset-write.md b/r/tests/testthat/_snaps/dataset-write.md index e302d8463d0f..03942fd85896 100644 --- a/r/tests/testthat/_snaps/dataset-write.md +++ b/r/tests/testthat/_snaps/dataset-write.md @@ -42,7 +42,7 @@ Condition Error in `check_additional_args()`: ! `nonsensical_arg` is not a valid argument for your chosen `format`. - i Supported arguments: `include_header`, `batch_size`, `null_string`, and `na`. + i Supported arguments: `include_header`, `batch_size`, `delimiter`, `null_string`, `eol`, `delim`, and `na`. --- diff --git a/r/tests/testthat/test-dataset-write.R b/r/tests/testthat/test-dataset-write.R index b8d2afe868a6..2e25f82110fc 100644 --- a/r/tests/testthat/test-dataset-write.R +++ b/r/tests/testthat/test-dataset-write.R @@ -813,7 +813,7 @@ test_that("write_dataset() errors on data.frame with NULL names", { expect_error(write_dataset(df, tempfile()), "Input data frame columns must be named") }) -test_that("Writing a dataset using write_csv_dataset wrapper", { +test_that("Writing a dataset to text files.", { df <- tibble( int = 1:10, dbl = as.numeric(1:10), @@ -821,6 +821,12 @@ test_that("Writing a dataset using write_csv_dataset wrapper", { chr = letters[1:10], ) + dst_dir <- make_temp_dir() + write_delim_dataset(df, dst_dir) + expect_true(dir.exists(dst_dir)) + new_ds <- open_dataset(dst_dir, format = "text") + expect_equal(new_ds %>% collect(), df) + dst_dir <- make_temp_dir() write_csv_dataset(df, dst_dir) expect_true(dir.exists(dst_dir)) @@ -828,27 +834,38 @@ test_that("Writing a dataset using write_csv_dataset wrapper", { expect_equal(new_ds %>% collect(), df) dst_dir <- make_temp_dir() - write_csv_dataset(df, dst_dir, include_header = FALSE) + write_tsv_dataset(df, dst_dir) expect_true(dir.exists(dst_dir)) - new_ds <- open_dataset(dst_dir, - format = "csv", - column_names = c("int", "dbl", "lgl", "chr") - ) + new_ds <- open_dataset(dst_dir, format = "tsv") expect_equal(new_ds %>% collect(), df) }) -test_that("Writing a csv dataset: `basename_template` default behavier", { +test_that("Writing a flat file dataset: `basename_template` default behavier", { ds <- open_dataset(csv_dir, partitioning = "part", format = "csv") + dst_dir <- make_temp_dir() + write_delim_dataset(ds, dst_dir, max_rows_per_file = 5L) + expect_identical( + dir(dst_dir, full.names = FALSE, recursive = TRUE), + paste0("part-", 0:3, ".txt") + ) + dst_dir <- make_temp_dir() write_csv_dataset(ds, dst_dir, max_rows_per_file = 5L) expect_identical( dir(dst_dir, full.names = FALSE, recursive = TRUE), paste0("part-", 0:3, ".csv") ) + + dst_dir <- make_temp_dir() + write_tsv_dataset(ds, dst_dir, max_rows_per_file = 5L) + expect_identical( + dir(dst_dir, full.names = FALSE, recursive = TRUE), + paste0("part-", 0:3, ".tsv") + ) }) -test_that("max_rows_per_group is adjusted if at odds with max_rows_per_file in write_csv_dataset()", { +test_that("max_rows_per_group is adjusted if at odds with max_rows_per_file in write_delim_dataset()", { skip_if_not_available("parquet") df <- tibble::tibble( int = 1:10, @@ -856,10 +873,60 @@ test_that("max_rows_per_group is adjusted if at odds with max_rows_per_file in w lgl = rep(c(TRUE, FALSE, NA, TRUE, FALSE), 2), chr = letters[1:10], ) - dst_dir <- make_temp_dir() # max_rows_per_group unset adjust silently + dst_dir <- make_temp_dir() + expect_silent( + write_delim_dataset(df, dst_dir, max_rows_per_file = 5) + ) + + dst_dir <- make_temp_dir() expect_silent( write_csv_dataset(df, dst_dir, max_rows_per_file = 5) ) + + dst_dir <- make_temp_dir() + expect_silent( + write_tsv_dataset(df, dst_dir, max_rows_per_file = 5) + ) +}) + +test_that("Writing a flat file dataset without a delimiter throws an error.", { + df <- tibble( + int = 1:10, + dbl = as.numeric(1:10), + lgl = rep(c(TRUE, FALSE, NA, TRUE, FALSE), 2), + chr = letters[1:10], + ) + + dst_dir <- make_temp_dir() + expect_error( + write_dataset(df, dst_dir, format = "txt"), + "A delimiter must be given for a txt format." + ) + + expect_error( + write_dataset(df, dst_dir, format = "text"), + "A delimiter must be given for a txt format." + ) +}) + +test_that("Writing a csv or tsv dataset with a delimiter throws an error.", { + df <- tibble( + int = 1:10, + dbl = as.numeric(1:10), + lgl = rep(c(TRUE, FALSE, NA, TRUE, FALSE), 2), + chr = letters[1:10], + ) + + dst_dir <- make_temp_dir() + expect_error( + write_dataset(df, dst_dir, format = "csv", delimiter = ","), + "Do not set a delimiter for csv or tsv formats." + ) + + expect_error( + write_dataset(df, dst_dir, format = "tsv", delimiter = "\t"), + "Do not set a delimiter for csv or tsv formats." + ) }) From 53bf0d02fb9eab877a4e083bf57868853d9b994e Mon Sep 17 00:00:00 2001 From: David Greiss Date: Sat, 15 Jul 2023 08:33:10 -0400 Subject: [PATCH 04/17] Resolve comments --- r/R/csv.R | 4 +--- r/R/dataset-write.R | 4 ---- r/tests/testthat/test-dataset-write.R | 20 -------------------- 3 files changed, 1 insertion(+), 27 deletions(-) diff --git a/r/R/csv.R b/r/R/csv.R index b531a160e357..c1dd3e102008 100644 --- a/r/R/csv.R +++ b/r/R/csv.R @@ -529,20 +529,18 @@ readr_to_csv_write_options <- function(include_header = TRUE, CsvWriteOptions <- R6Class("CsvWriteOptions", inherit = ArrowObject) CsvWriteOptions$create <- function(include_header = TRUE, batch_size = 1024L, - delimiter = ",", null_string = "", + delimiter = ",", eol = "\n") { assert_that(is.logical(include_header)) assert_that(is_integerish(batch_size, n = 1, finite = TRUE), batch_size > 0) assert_that(is.character(delimiter)) - assert_that(is.character(null_string)) assert_that(!is.na(null_string)) assert_that(length(null_string) == 1) assert_that(!grepl('"', null_string), msg = "na argument must not contain quote characters.") - assert_that(is.character(eol)) csv___WriteOptions__initialize( diff --git a/r/R/dataset-write.R b/r/R/dataset-write.R index 5c83082ca978..0cd3f67ed3a7 100644 --- a/r/R/dataset-write.R +++ b/r/R/dataset-write.R @@ -180,10 +180,6 @@ write_dataset <- function(dataset, path_and_fs <- get_path_and_filesystem(path) dots <- list(...) - if (format %in% c("csv", "tsv") && any(c("delimiter", "delim") %in% names(dots))) { - stop("Do not set a delimiter for csv or tsv formats.") - } - if (format %in% c("txt", "text") && !any(c("delimiter", "delim") %in% names(dots))) { stop("A delimiter must be given for a txt format.") } diff --git a/r/tests/testthat/test-dataset-write.R b/r/tests/testthat/test-dataset-write.R index 2e25f82110fc..1067df029ab2 100644 --- a/r/tests/testthat/test-dataset-write.R +++ b/r/tests/testthat/test-dataset-write.R @@ -910,23 +910,3 @@ test_that("Writing a flat file dataset without a delimiter throws an error.", { "A delimiter must be given for a txt format." ) }) - -test_that("Writing a csv or tsv dataset with a delimiter throws an error.", { - df <- tibble( - int = 1:10, - dbl = as.numeric(1:10), - lgl = rep(c(TRUE, FALSE, NA, TRUE, FALSE), 2), - chr = letters[1:10], - ) - - dst_dir <- make_temp_dir() - expect_error( - write_dataset(df, dst_dir, format = "csv", delimiter = ","), - "Do not set a delimiter for csv or tsv formats." - ) - - expect_error( - write_dataset(df, dst_dir, format = "tsv", delimiter = "\t"), - "Do not set a delimiter for csv or tsv formats." - ) -}) From d041774afc8250b78126fddd9813f5a20aa6a334 Mon Sep 17 00:00:00 2001 From: David Greiss Date: Sun, 16 Jul 2023 17:59:38 -0400 Subject: [PATCH 05/17] Expose readr::write_csv() options --- r/R/csv.R | 6 +- r/R/dataset-format.R | 3 + r/R/dataset-write.R | 95 ++++++++---------------- r/tests/testthat/_snaps/dataset-write.md | 2 +- r/tests/testthat/test-dataset-write.R | 33 ++++++++ 5 files changed, 73 insertions(+), 66 deletions(-) diff --git a/r/R/csv.R b/r/R/csv.R index c1dd3e102008..cb1eef7059a1 100644 --- a/r/R/csv.R +++ b/r/R/csv.R @@ -510,13 +510,13 @@ CsvReadOptions$create <- function(use_threads = option_use_threads(), options } -readr_to_csv_write_options <- function(include_header = TRUE, +readr_to_csv_write_options <- function(col_names = TRUE, batch_size = 1024L, delim = ",", na = "", eol = "\n") { CsvWriteOptions$create( - include_header = include_header, + include_header = col_names, batch_size = batch_size, delimiter = delim, null_string = na, @@ -801,7 +801,7 @@ write_csv_arrow <- function(x, if (is.null(write_options)) { write_options <- readr_to_csv_write_options( - include_header = include_header, + col_names = include_header, batch_size = batch_size, na = na ) diff --git a/r/R/dataset-format.R b/r/R/dataset-format.R index f48d8cfa0cba..d41894ebdf8e 100644 --- a/r/R/dataset-format.R +++ b/r/R/dataset-format.R @@ -688,6 +688,9 @@ FileWriteOptions <- R6Class("FileWriteOptions", is_arrow_opt <- !is.na(pmatch(names(args), arrow_opts)) is_readr_opt <- !is.na(pmatch(names(args), readr_opts)) is_readr_only_opt <- !is.na(pmatch(names(args), readr_only_opts)) + if (any(is_arrow_opt) && any(is_readr_only_opt)) { + stop("Can't write dataset with both Arrow options and readr options.") + } # These option names aren't mutually exclusive, so only use readr path # if we have at least one readr-specific option. diff --git a/r/R/dataset-write.R b/r/R/dataset-write.R index 0cd3f67ed3a7..f48137386f89 100644 --- a/r/R/dataset-write.R +++ b/r/R/dataset-write.R @@ -294,28 +294,17 @@ write_delim_dataset <- function(dataset, max_rows_per_file = 0L, min_rows_per_group = 0L, max_rows_per_group = bitwShiftL(1, 20), - delimiter = ",", - ...) { - if (!missing(max_rows_per_file) && missing(max_rows_per_group) && max_rows_per_group > max_rows_per_file) { - max_rows_per_group <- max_rows_per_file - } - - write_dataset( - dataset = dataset, - path = path, - format = "txt", - partitioning = partitioning, - basename_template = basename_template, - hive_style = hive_style, - existing_data_behavior = existing_data_behavior, - max_partitions = max_partitions, - max_open_files = max_open_files, - max_rows_per_file = max_rows_per_file, - min_rows_per_group = min_rows_per_group, - max_rows_per_group = max_rows_per_group, - delimiter = delimiter, - ... - ) + col_names = TRUE, + delim = ",", + na = "", + eol = "\n") { + mc <- match.call() + mc$format <- "txt" + mc$include_header <- col_names + mc$delimiter <- delim + mc$null_string <- na + mc[[1]] <- get("write_dataset", envir = asNamespace("arrow")) + eval.parent(mc) } #' @rdname write_delim_dataset @@ -331,26 +320,17 @@ write_csv_dataset <- function(dataset, max_rows_per_file = 0L, min_rows_per_group = 0L, max_rows_per_group = bitwShiftL(1, 20), - ...) { - if (!missing(max_rows_per_file) && missing(max_rows_per_group) && max_rows_per_group > max_rows_per_file) { - max_rows_per_group <- max_rows_per_file - } - - write_dataset( - dataset = dataset, - path = path, - format = "csv", - partitioning = partitioning, - basename_template = basename_template, - hive_style = hive_style, - existing_data_behavior = existing_data_behavior, - max_partitions = max_partitions, - max_open_files = max_open_files, - max_rows_per_file = max_rows_per_file, - min_rows_per_group = min_rows_per_group, - max_rows_per_group = max_rows_per_group, - ... - ) + col_names = TRUE, + delim = ",", + na = "", + eol = "\n") { + mc <- match.call() + mc$format <- "csv" + mc$include_header <- col_names + mc$delimiter <- delim + mc$null_string <- na + mc[[1]] <- get("write_dataset", envir = asNamespace("arrow")) + eval.parent(mc) } #' @rdname write_delim_dataset @@ -366,26 +346,17 @@ write_tsv_dataset <- function(dataset, max_rows_per_file = 0L, min_rows_per_group = 0L, max_rows_per_group = bitwShiftL(1, 20), - ...) { - if (!missing(max_rows_per_file) && missing(max_rows_per_group) && max_rows_per_group > max_rows_per_file) { - max_rows_per_group <- max_rows_per_file - } - - write_dataset( - dataset = dataset, - path = path, - format = "tsv", - partitioning = partitioning, - basename_template = basename_template, - hive_style = hive_style, - existing_data_behavior = existing_data_behavior, - max_partitions = max_partitions, - max_open_files = max_open_files, - max_rows_per_file = max_rows_per_file, - min_rows_per_group = min_rows_per_group, - max_rows_per_group = max_rows_per_group, - ... - ) + col_names = TRUE, + delim = "\t", + na = "", + eol = "\n") { + mc <- match.call() + mc$format <- "tsv" + mc$include_header <- col_names + mc$delimiter <- delim + mc$null_string <- na + mc[[1]] <- get("write_dataset", envir = asNamespace("arrow")) + eval.parent(mc) } validate_positive_int_value <- function(value, msg) { diff --git a/r/tests/testthat/_snaps/dataset-write.md b/r/tests/testthat/_snaps/dataset-write.md index 03942fd85896..4a05f625a5c8 100644 --- a/r/tests/testthat/_snaps/dataset-write.md +++ b/r/tests/testthat/_snaps/dataset-write.md @@ -42,7 +42,7 @@ Condition Error in `check_additional_args()`: ! `nonsensical_arg` is not a valid argument for your chosen `format`. - i Supported arguments: `include_header`, `batch_size`, `delimiter`, `null_string`, `eol`, `delim`, and `na`. + i Supported arguments: `include_header`, `batch_size`, `null_string`, `delimiter`, `eol`, `col_names`, `delim`, and `na`. --- diff --git a/r/tests/testthat/test-dataset-write.R b/r/tests/testthat/test-dataset-write.R index 1067df029ab2..9842931c37f8 100644 --- a/r/tests/testthat/test-dataset-write.R +++ b/r/tests/testthat/test-dataset-write.R @@ -910,3 +910,36 @@ test_that("Writing a flat file dataset without a delimiter throws an error.", { "A delimiter must be given for a txt format." ) }) + +test_that("readr::write_csv() options for flat files.", { + df <- tibble( + int = 1:10, + dbl = as.numeric(1:10), + lgl = rep(c(TRUE, FALSE, NA, TRUE, FALSE), 2), + chr = letters[1:10], + ) + + dst_dir <- make_temp_dir() + write_dataset(df, dst_dir, format = "csv", col_names = FALSE) + expect_true(dir.exists(dst_dir)) + + header <- readLines(file(paste0(dst_dir, "/part-0.csv")), n = 1L) + expect_equal(header, "1,1,true,\"a\"") + + df2 <- tibble(x = "") + dst_dir <- make_temp_dir() + write_dataset(df2, dst_dir, format = "csv", eol = "\r\n") + expect_true(dir.exists(dst_dir)) + + header <- readBin(con <- file(paste0(dst_dir, "/part-0.csv"), "rb"), "raw", n = 5) + close(con) + + # 0d and 0a are the character codes of CRLF (https://www.asciitable.com) + expect_equal(as.character(header[4:5]), c("0d", "0a")) + + dst_dir <- make_temp_dir() + expect_error( + write_dataset(df, dst_dir, format = "csv", col_names = FALSE, delim = ";"), + "Can't write dataset with both Arrow options and readr options." + ) +}) From 117ee51a05c4520b7df249e7dd857d4e0df681b9 Mon Sep 17 00:00:00 2001 From: David Greiss Date: Sun, 16 Jul 2023 21:55:47 -0400 Subject: [PATCH 06/17] Update docs --- r/R/dataset-write.R | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/r/R/dataset-write.R b/r/R/dataset-write.R index f48137386f89..e11c231e6ede 100644 --- a/r/R/dataset-write.R +++ b/r/R/dataset-write.R @@ -274,12 +274,14 @@ write_dataset <- function(dataset, #' group and when this number of rows is exceeded, it is split and the next set #' of rows is written to the next group. This value must be set such that it is #' greater than `min_rows_per_group`. Default is 1024 * 1024. -#' @param delimiter Delimiter used to separate values. Defaults to `","` for `write_delim_dataset()` and +#' @param col_names whether to write an initial header line with column names +#' @param delim delimiter used to separate values. Defaults to `","` for `write_delim_dataset()` and #' `write_csv_dataset()`, and `"\t` for `write_tsv_dataset()`. Cannot be changed for `write_csv_dataset()` #' and `write_tsv_dataset()`. -#' @param ... additional format-specific arguments. For available CSV -#' options, see [CsvWriteOptions]. -#' @return The input `dataset`, invisibly +#' @param na a character vector of strings to interpret as missing values. Quotes are not allowed in this string. +#' The default is an empty string `""`. +#' @param eol the end of line character to use for ending rows. The default is `"\n"`. +#' @return The input `dataset`, invisibly. #' #' @seealso [write_dataset()] #' @export From b342d23699620796c4f4518585d1d9bc220809ee Mon Sep 17 00:00:00 2001 From: David Greiss Date: Sun, 16 Jul 2023 22:11:56 -0400 Subject: [PATCH 07/17] Add batch_size option --- r/R/dataset-write.R | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/r/R/dataset-write.R b/r/R/dataset-write.R index e11c231e6ede..ae18d2606187 100644 --- a/r/R/dataset-write.R +++ b/r/R/dataset-write.R @@ -274,7 +274,8 @@ write_dataset <- function(dataset, #' group and when this number of rows is exceeded, it is split and the next set #' of rows is written to the next group. This value must be set such that it is #' greater than `min_rows_per_group`. Default is 1024 * 1024. -#' @param col_names whether to write an initial header line with column names +#' @param col_names whether to write an initial header line with column names. +#' @param batch_size maximum number of rows processed at a time. Default is 1024. #' @param delim delimiter used to separate values. Defaults to `","` for `write_delim_dataset()` and #' `write_csv_dataset()`, and `"\t` for `write_tsv_dataset()`. Cannot be changed for `write_csv_dataset()` #' and `write_tsv_dataset()`. @@ -297,6 +298,7 @@ write_delim_dataset <- function(dataset, min_rows_per_group = 0L, max_rows_per_group = bitwShiftL(1, 20), col_names = TRUE, + batch_size = 1024L, delim = ",", na = "", eol = "\n") { @@ -323,6 +325,7 @@ write_csv_dataset <- function(dataset, min_rows_per_group = 0L, max_rows_per_group = bitwShiftL(1, 20), col_names = TRUE, + batch_size = 1024L, delim = ",", na = "", eol = "\n") { @@ -349,6 +352,7 @@ write_tsv_dataset <- function(dataset, min_rows_per_group = 0L, max_rows_per_group = bitwShiftL(1, 20), col_names = TRUE, + batch_size = 1024L, delim = "\t", na = "", eol = "\n") { From e7aeee2e8f56ea34071aaa480c8cbcf833613daa Mon Sep 17 00:00:00 2001 From: David Greiss Date: Mon, 17 Jul 2023 13:34:55 -0400 Subject: [PATCH 08/17] Add quoting_style option --- r/R/csv.R | 21 +++- r/R/dataset-format.R | 11 +- r/R/dataset-write.R | 141 ++++++++++++++++------- r/src/csv.cpp | 2 + r/tests/testthat/_snaps/dataset-write.md | 2 +- r/tests/testthat/test-dataset-write.R | 69 ++++++++++- 6 files changed, 190 insertions(+), 56 deletions(-) diff --git a/r/R/csv.R b/r/R/csv.R index cb1eef7059a1..32ef054f1dde 100644 --- a/r/R/csv.R +++ b/r/R/csv.R @@ -514,13 +514,15 @@ readr_to_csv_write_options <- function(col_names = TRUE, batch_size = 1024L, delim = ",", na = "", - eol = "\n") { + eol = "\n", + quote = "Needed") { CsvWriteOptions$create( include_header = col_names, batch_size = batch_size, delimiter = delim, null_string = na, - eol = eol + eol = eol, + quoting_style = quote ) } @@ -531,25 +533,32 @@ CsvWriteOptions$create <- function(include_header = TRUE, batch_size = 1024L, null_string = "", delimiter = ",", - eol = "\n") { - assert_that(is.logical(include_header)) + eol = "\n", + quoting_style = c("Needed", "AllValid", "None")) { + if (missing(quoting_style)) { + quoting_style <- "Needed" + } + quoting_style_opts <- c("Needed", "AllValid", "None") + assert_that(is.logical(include_header)) assert_that(is_integerish(batch_size, n = 1, finite = TRUE), batch_size > 0) - assert_that(is.character(delimiter)) assert_that(is.character(null_string)) assert_that(!is.na(null_string)) assert_that(length(null_string) == 1) assert_that(!grepl('"', null_string), msg = "na argument must not contain quote characters.") assert_that(is.character(eol)) + assert_that(quoting_style %in% quoting_style_opts, msg = "quoting_style must be 1 of 'Needed', 'AllValid' or 'None'") + quoting_style <- match(match.arg(quoting_style), quoting_style_opts) - 1L csv___WriteOptions__initialize( list( include_header = include_header, batch_size = as.integer(batch_size), delimiter = delimiter, null_string = as.character(null_string), - eol = eol + eol = eol, + quoting_style = quoting_style ) ) } diff --git a/r/R/dataset-format.R b/r/R/dataset-format.R index d41894ebdf8e..05410841258f 100644 --- a/r/R/dataset-format.R +++ b/r/R/dataset-format.R @@ -684,11 +684,14 @@ FileWriteOptions <- R6Class("FileWriteOptions", arrow_opts <- names(formals(CsvWriteOptions$create)) readr_opts <- names(formals(readr_to_csv_write_options)) readr_only_opts <- setdiff(readr_opts, arrow_opts) + arrow_only_opts <- setdiff(arrow_opts, readr_opts) - is_arrow_opt <- !is.na(pmatch(names(args), arrow_opts)) - is_readr_opt <- !is.na(pmatch(names(args), readr_opts)) - is_readr_only_opt <- !is.na(pmatch(names(args), readr_only_opts)) - if (any(is_arrow_opt) && any(is_readr_only_opt)) { + is_arrow_opt <- !is.na(match(names(args), arrow_opts)) + is_readr_opt <- !is.na(match(names(args), readr_opts)) + is_arrow_only_opt <- !is.na(match(names(args), arrow_only_opts)) + is_readr_only_opt <- !is.na(match(names(args), readr_only_opts)) + + if (any(is_arrow_only_opt) && any(is_readr_only_opt)) { stop("Can't write dataset with both Arrow options and readr options.") } diff --git a/r/R/dataset-write.R b/r/R/dataset-write.R index ae18d2606187..6aa50b4593c2 100644 --- a/r/R/dataset-write.R +++ b/r/R/dataset-write.R @@ -183,6 +183,9 @@ write_dataset <- function(dataset, if (format %in% c("txt", "text") && !any(c("delimiter", "delim") %in% names(dots))) { stop("A delimiter must be given for a txt format.") } + if (format == "tsv" && any(c("delimiter", "delim") %in% names(dots))) { + stop("Can't set a delimiter for the tsv format.") + } output_schema <- final_node$schema # This is a workaround because CsvFileFormat$create defaults the delimiter to "," @@ -234,54 +237,61 @@ write_dataset <- function(dataset, #' `data.frame`. If an `arrow_dplyr_query`, the query will be evaluated and #' the result will be written. This means that you can `select()`, `filter()`, `mutate()`, #' etc. to transform the data before it is written if you need to. -#' @param path string path, URI, or `SubTreeFileSystem` referencing a directory +#' @param path String path, URI, or `SubTreeFileSystem` referencing a directory #' to write to (directory will be created if it does not exist) #' @param partitioning `Partitioning` or a character vector of columns to #' use as partition keys (to be written as path segments). Default is to #' use the current `group_by()` columns. -#' @param basename_template string template for the names of files to be written. +#' @param basename_template String template for the names of files to be written. #' Must contain `"{i}"`, which will be replaced with an autoincremented #' integer to generate basenames of datafiles. For example, `"part-{i}.csv"` #' will yield `"part-0.csv", ...`. #' If not specified, it defaults to `"part-{i}.csv"`. -#' @param hive_style logical: write partition segments as Hive-style +#' @param hive_style Write partition segments as Hive-style #' (`key1=value1/key2=value2/file.ext`) or as just bare values. Default is `TRUE`. #' @param existing_data_behavior The behavior to use when there is already data #' in the destination directory. Must be one of "overwrite", "error", or #' "delete_matching". -#' - "overwrite" (the default) then any new files created will overwrite +#' - `overwrite` (the default) then any new files created will overwrite #' existing files -#' - "error" then the operation will fail if the destination directory is not +#' - `error` then the operation will fail if the destination directory is not #' empty -#' - "delete_matching" then the writer will delete any existing partitions +#' - `delete_matching` then the writer will delete any existing partitions #' if data is going to be written to those partitions and will leave alone #' partitions which data is not written to. -#' @param max_partitions maximum number of partitions any batch may be +#' @param max_partitions Maximum number of partitions any batch may be #' written into. Default is 1024L. -#' @param max_open_files maximum number of files that can be left opened +#' @param max_open_files Maximum number of files that can be left opened #' during a write operation. If greater than 0 then this will limit the #' maximum number of files that can be left open. If an attempt is made to open #' too many files then the least recently used file will be closed. #' If this setting is set too low you may end up fragmenting your data #' into many small files. The default is 900 which also allows some # of files to be #' open by the scanner before hitting the default Linux limit of 1024. -#' @param max_rows_per_file maximum number of rows per file. +#' @param max_rows_per_file Maximum number of rows per file. #' If greater than 0 then this will limit how many rows are placed in any single file. #' Default is 0L. -#' @param min_rows_per_group write the row groups to the disk when this number of +#' @param min_rows_per_group Write the row groups to the disk when this number of #' rows have accumulated. Default is 0L. -#' @param max_rows_per_group maximum rows allowed in a single +#' @param max_rows_per_group Maximum rows allowed in a single #' group and when this number of rows is exceeded, it is split and the next set #' of rows is written to the next group. This value must be set such that it is #' greater than `min_rows_per_group`. Default is 1024 * 1024. -#' @param col_names whether to write an initial header line with column names. -#' @param batch_size maximum number of rows processed at a time. Default is 1024. -#' @param delim delimiter used to separate values. Defaults to `","` for `write_delim_dataset()` and -#' `write_csv_dataset()`, and `"\t` for `write_tsv_dataset()`. Cannot be changed for `write_csv_dataset()` -#' and `write_tsv_dataset()`. +#' @param col_names Whether to write an initial header line with column names. +#' @param batch_size Maximum number of rows processed at a time. Default is 1024L. +#' @param delim Delimiter used to separate values. Defaults to `","` for `write_delim_dataset()` and +#' `write_csv_dataset()`, and `"\t` for `write_tsv_dataset()`. Cannot be changed for `write_tsv_dataset()`. #' @param na a character vector of strings to interpret as missing values. Quotes are not allowed in this string. #' The default is an empty string `""`. #' @param eol the end of line character to use for ending rows. The default is `"\n"`. +#' @param quote How to handle fields which contain characters that need to be quoted. +#' - `Needed` - Only enclose values in quotes which need them, because their CSV rendering can +#' contain quotes itself (e.g. strings or binary values) (the default) +#' - `AllValid` - Enclose all valid values in quotes. Nulls are not quoted. May cause readers to +#' interpret all values as strings if schema is inferred. +#' - `None` - Do not enclose any values in quotes. Prevents values from containing quotes ("), +#' cell delimiters (,) or line endings (\\r, \\n), (following RFC4180). If values +#' contain these characters, an error is caused when attempting to write. #' @return The input `dataset`, invisibly. #' #' @seealso [write_dataset()] @@ -301,14 +311,31 @@ write_delim_dataset <- function(dataset, batch_size = 1024L, delim = ",", na = "", - eol = "\n") { - mc <- match.call() - mc$format <- "txt" - mc$include_header <- col_names - mc$delimiter <- delim - mc$null_string <- na - mc[[1]] <- get("write_dataset", envir = asNamespace("arrow")) - eval.parent(mc) + eol = "\n", + quote = "Needed") { + if (!missing(max_rows_per_file) && missing(max_rows_per_group) && max_rows_per_group > max_rows_per_file) { + max_rows_per_group <- max_rows_per_file + } + write_dataset( + dataset = dataset, + path = path, + format = "txt", + partitioning = partitioning, + basename_template = basename_template, + hive_style = hive_style, + existing_data_behavior = existing_data_behavior, + max_partitions = max_partitions, + max_open_files = max_open_files, + max_rows_per_file = max_rows_per_file, + min_rows_per_group = min_rows_per_group, + max_rows_per_group = max_rows_per_group, + include_header = col_names, + batch_size = batch_size, + delimiter = delim, + null_string = na, + eol = eol, + quoting_style = quote + ) } #' @rdname write_delim_dataset @@ -328,14 +355,31 @@ write_csv_dataset <- function(dataset, batch_size = 1024L, delim = ",", na = "", - eol = "\n") { - mc <- match.call() - mc$format <- "csv" - mc$include_header <- col_names - mc$delimiter <- delim - mc$null_string <- na - mc[[1]] <- get("write_dataset", envir = asNamespace("arrow")) - eval.parent(mc) + eol = "\n", + quote = "Needed") { + if (!missing(max_rows_per_file) && missing(max_rows_per_group) && max_rows_per_group > max_rows_per_file) { + max_rows_per_group <- max_rows_per_file + } + write_dataset( + dataset = dataset, + path = path, + format = "csv", + partitioning = partitioning, + basename_template = basename_template, + hive_style = hive_style, + existing_data_behavior = existing_data_behavior, + max_partitions = max_partitions, + max_open_files = max_open_files, + max_rows_per_file = max_rows_per_file, + min_rows_per_group = min_rows_per_group, + max_rows_per_group = max_rows_per_group, + include_header = col_names, + batch_size = batch_size, + delimiter = delim, + null_string = na, + eol = eol, + quoting_style = quote + ) } #' @rdname write_delim_dataset @@ -353,16 +397,31 @@ write_tsv_dataset <- function(dataset, max_rows_per_group = bitwShiftL(1, 20), col_names = TRUE, batch_size = 1024L, - delim = "\t", na = "", - eol = "\n") { - mc <- match.call() - mc$format <- "tsv" - mc$include_header <- col_names - mc$delimiter <- delim - mc$null_string <- na - mc[[1]] <- get("write_dataset", envir = asNamespace("arrow")) - eval.parent(mc) + eol = "\n", + quote = "Needed") { + if (!missing(max_rows_per_file) && missing(max_rows_per_group) && max_rows_per_group > max_rows_per_file) { + max_rows_per_group <- max_rows_per_file + } + write_dataset( + dataset = dataset, + path = path, + format = "tsv", + partitioning = partitioning, + basename_template = basename_template, + hive_style = hive_style, + existing_data_behavior = existing_data_behavior, + max_partitions = max_partitions, + max_open_files = max_open_files, + max_rows_per_file = max_rows_per_file, + min_rows_per_group = min_rows_per_group, + max_rows_per_group = max_rows_per_group, + include_header = col_names, + batch_size = batch_size, + null_string = na, + eol = eol, + quoting_style = quote + ) } validate_positive_int_value <- function(value, msg) { diff --git a/r/src/csv.cpp b/r/src/csv.cpp index a0f534e1587e..ffb8a11e6b4e 100644 --- a/r/src/csv.cpp +++ b/r/src/csv.cpp @@ -35,6 +35,8 @@ std::shared_ptr csv___WriteOptions__initialize( res->null_string = cpp11::as_cpp(options["null_string"]); res->io_context = MainRThread::GetInstance().CancellableIOContext(); res->eol = cpp11::as_cpp(options["eol"]); + res->quoting_style = + cpp11::as_cpp(options["quoting_style"]); return res; } diff --git a/r/tests/testthat/_snaps/dataset-write.md b/r/tests/testthat/_snaps/dataset-write.md index 4a05f625a5c8..19f687be6716 100644 --- a/r/tests/testthat/_snaps/dataset-write.md +++ b/r/tests/testthat/_snaps/dataset-write.md @@ -42,7 +42,7 @@ Condition Error in `check_additional_args()`: ! `nonsensical_arg` is not a valid argument for your chosen `format`. - i Supported arguments: `include_header`, `batch_size`, `null_string`, `delimiter`, `eol`, `col_names`, `delim`, and `na`. + i Supported arguments: `include_header`, `batch_size`, `null_string`, `delimiter`, `eol`, `quoting_style`, `col_names`, `delim`, `na`, and `quote`. --- diff --git a/r/tests/testthat/test-dataset-write.R b/r/tests/testthat/test-dataset-write.R index 9842931c37f8..95ae046d1160 100644 --- a/r/tests/testthat/test-dataset-write.R +++ b/r/tests/testthat/test-dataset-write.R @@ -813,7 +813,7 @@ test_that("write_dataset() errors on data.frame with NULL names", { expect_error(write_dataset(df, tempfile()), "Input data frame columns must be named") }) -test_that("Writing a dataset to text files.", { +test_that("Writing a dataset to text files with wrapper functions.", { df <- tibble( int = 1:10, dbl = as.numeric(1:10), @@ -911,7 +911,7 @@ test_that("Writing a flat file dataset without a delimiter throws an error.", { ) }) -test_that("readr::write_csv() options for flat files.", { +test_that("Dataset can write flat files using readr::write_csv() options.", { df <- tibble( int = 1:10, dbl = as.numeric(1:10), @@ -934,12 +934,73 @@ test_that("readr::write_csv() options for flat files.", { header <- readBin(con <- file(paste0(dst_dir, "/part-0.csv"), "rb"), "raw", n = 5) close(con) - # 0d and 0a are the character codes of CRLF (https://www.asciitable.com) + # 0d and 0a are the character codes for CRLF (https://www.asciitable.com) expect_equal(as.character(header[4:5]), c("0d", "0a")) dst_dir <- make_temp_dir() expect_error( - write_dataset(df, dst_dir, format = "csv", col_names = FALSE, delim = ";"), + write_dataset(df, dst_dir, format = "csv", include_header = FALSE, delim = ";"), "Can't write dataset with both Arrow options and readr options." ) + dst_dir <- make_temp_dir() + write_dataset(df, dst_dir, format = "csv", quote = "AllValid") + ds <- open_dataset(dst_dir, format = "csv") + expect_equal(df, ds |> collect()) + + expect_error( + write_dataset(df, dst_dir, format = "csv", quote = "foobar"), + "quoting_style must be 1 of 'Needed', 'AllValid' or 'None'" + ) + + expect_error( + write_dataset(df, dst_dir, format = "tsv", delimiter = ";"), + "Can't set a delimiter for the tsv format." + ) +}) + +test_that("Dataset write wrappers can write flat files using readr::write_csv() options.", { + df <- tibble( + int = 1:10, + dbl = as.numeric(1:10), + lgl = rep(c(TRUE, FALSE, NA, TRUE, FALSE), 2), + chr = letters[1:10], + ) + + dst_dir <- make_temp_dir() + write_csv_dataset(df, dst_dir, col_names = FALSE) + + header <- readLines(file(paste0(dst_dir, "/part-0.csv")), n = 1L) + expect_equal(header, "1,1,true,\"a\"") + + dst_dir <- make_temp_dir() + write_tsv_dataset(df, dst_dir, col_names = FALSE) + + header <- readLines(file(paste0(dst_dir, "/part-0.tsv")), n = 1L) + expect_equal(header, "1\t1\ttrue\t\"a\"") + + df2 <- tibble(x = "") + dst_dir <- make_temp_dir() + write_csv_dataset(df2, dst_dir, eol = "\r\n") + header <- readBin(con <- file(paste0(dst_dir, "/part-0.csv"), "rb"), "raw", n = 5) + close(con) + # 0d and 0a are the character codes for CRLF (https://www.asciitable.com) + expect_equal(as.character(header[4:5]), c("0d", "0a")) + + df2 <- tibble(x = "") + dst_dir <- make_temp_dir() + write_tsv_dataset(df2, dst_dir, eol = "\r\n") + header <- readBin(con <- file(paste0(dst_dir, "/part-0.tsv"), "rb"), "raw", n = 5) + close(con) + # 0d and 0a are the character codes for CRLF (https://www.asciitable.com) + expect_equal(as.character(header[4:5]), c("0d", "0a")) + + dst_dir <- make_temp_dir() + write_csv_dataset(df, dst_dir, quote = "AllValid", delim = ";") + ds <- open_dataset(dst_dir, format = "csv", delim = ";") + expect_equal(df, ds |> collect()) + + dst_dir <- make_temp_dir() + write_tsv_dataset(df, dst_dir, quote = "AllValid", eol = "\r\n") + ds <- open_dataset(dst_dir, format = "tsv") + expect_equal(df, ds |> collect()) }) From c41f75f86dc14bc37670f0f1ec52b77d1458523b Mon Sep 17 00:00:00 2001 From: David Greiss Date: Mon, 7 Aug 2023 11:30:45 -0400 Subject: [PATCH 09/17] Resolve comments --- r/R/csv.R | 7 ++-- r/R/dataset-format.R | 2 +- r/R/dataset-write.R | 51 +++------------------------ r/tests/testthat/test-dataset-write.R | 15 ++++---- 4 files changed, 14 insertions(+), 61 deletions(-) diff --git a/r/R/csv.R b/r/R/csv.R index 32ef054f1dde..82bdd78a3f9c 100644 --- a/r/R/csv.R +++ b/r/R/csv.R @@ -535,10 +535,9 @@ CsvWriteOptions$create <- function(include_header = TRUE, delimiter = ",", eol = "\n", quoting_style = c("Needed", "AllValid", "None")) { - if (missing(quoting_style)) { - quoting_style <- "Needed" - } + quoting_style <- match.arg(quoting_style) quoting_style_opts <- c("Needed", "AllValid", "None") + quoting_style <- match(quoting_style, quoting_style_opts) - 1L assert_that(is.logical(include_header)) assert_that(is_integerish(batch_size, n = 1, finite = TRUE), batch_size > 0) @@ -548,9 +547,7 @@ CsvWriteOptions$create <- function(include_header = TRUE, assert_that(length(null_string) == 1) assert_that(!grepl('"', null_string), msg = "na argument must not contain quote characters.") assert_that(is.character(eol)) - assert_that(quoting_style %in% quoting_style_opts, msg = "quoting_style must be 1 of 'Needed', 'AllValid' or 'None'") - quoting_style <- match(match.arg(quoting_style), quoting_style_opts) - 1L csv___WriteOptions__initialize( list( include_header = include_header, diff --git a/r/R/dataset-format.R b/r/R/dataset-format.R index 05410841258f..ed5e81b0e782 100644 --- a/r/R/dataset-format.R +++ b/r/R/dataset-format.R @@ -692,7 +692,7 @@ FileWriteOptions <- R6Class("FileWriteOptions", is_readr_only_opt <- !is.na(match(names(args), readr_only_opts)) if (any(is_arrow_only_opt) && any(is_readr_only_opt)) { - stop("Can't write dataset with both Arrow options and readr options.") + stop("Use either Arrow write options or readr write options, not both") } # These option names aren't mutually exclusive, so only use readr path diff --git a/r/R/dataset-write.R b/r/R/dataset-write.R index 6aa50b4593c2..c4af9f37b337 100644 --- a/r/R/dataset-write.R +++ b/r/R/dataset-write.R @@ -233,50 +233,7 @@ write_dataset <- function(dataset, #' The `write_*_dataset()` are a family of wrappers around [write_dataset] to allow for easy switching #' between functions for writing datasets. #' -#' @param dataset [Dataset], [RecordBatch], [Table], `arrow_dplyr_query`, or -#' `data.frame`. If an `arrow_dplyr_query`, the query will be evaluated and -#' the result will be written. This means that you can `select()`, `filter()`, `mutate()`, -#' etc. to transform the data before it is written if you need to. -#' @param path String path, URI, or `SubTreeFileSystem` referencing a directory -#' to write to (directory will be created if it does not exist) -#' @param partitioning `Partitioning` or a character vector of columns to -#' use as partition keys (to be written as path segments). Default is to -#' use the current `group_by()` columns. -#' @param basename_template String template for the names of files to be written. -#' Must contain `"{i}"`, which will be replaced with an autoincremented -#' integer to generate basenames of datafiles. For example, `"part-{i}.csv"` -#' will yield `"part-0.csv", ...`. -#' If not specified, it defaults to `"part-{i}.csv"`. -#' @param hive_style Write partition segments as Hive-style -#' (`key1=value1/key2=value2/file.ext`) or as just bare values. Default is `TRUE`. -#' @param existing_data_behavior The behavior to use when there is already data -#' in the destination directory. Must be one of "overwrite", "error", or -#' "delete_matching". -#' - `overwrite` (the default) then any new files created will overwrite -#' existing files -#' - `error` then the operation will fail if the destination directory is not -#' empty -#' - `delete_matching` then the writer will delete any existing partitions -#' if data is going to be written to those partitions and will leave alone -#' partitions which data is not written to. -#' @param max_partitions Maximum number of partitions any batch may be -#' written into. Default is 1024L. -#' @param max_open_files Maximum number of files that can be left opened -#' during a write operation. If greater than 0 then this will limit the -#' maximum number of files that can be left open. If an attempt is made to open -#' too many files then the least recently used file will be closed. -#' If this setting is set too low you may end up fragmenting your data -#' into many small files. The default is 900 which also allows some # of files to be -#' open by the scanner before hitting the default Linux limit of 1024. -#' @param max_rows_per_file Maximum number of rows per file. -#' If greater than 0 then this will limit how many rows are placed in any single file. -#' Default is 0L. -#' @param min_rows_per_group Write the row groups to the disk when this number of -#' rows have accumulated. Default is 0L. -#' @param max_rows_per_group Maximum rows allowed in a single -#' group and when this number of rows is exceeded, it is split and the next set -#' of rows is written to the next group. This value must be set such that it is -#' greater than `min_rows_per_group`. Default is 1024 * 1024. +#' @inheritParams [write_dataset()] #' @param col_names Whether to write an initial header line with column names. #' @param batch_size Maximum number of rows processed at a time. Default is 1024L. #' @param delim Delimiter used to separate values. Defaults to `","` for `write_delim_dataset()` and @@ -312,7 +269,7 @@ write_delim_dataset <- function(dataset, delim = ",", na = "", eol = "\n", - quote = "Needed") { + quote = c("Needed", "AllValid", "None")) { if (!missing(max_rows_per_file) && missing(max_rows_per_group) && max_rows_per_group > max_rows_per_file) { max_rows_per_group <- max_rows_per_file } @@ -356,7 +313,7 @@ write_csv_dataset <- function(dataset, delim = ",", na = "", eol = "\n", - quote = "Needed") { + quote = c("Needed", "AllValid", "None")) { if (!missing(max_rows_per_file) && missing(max_rows_per_group) && max_rows_per_group > max_rows_per_file) { max_rows_per_group <- max_rows_per_file } @@ -399,7 +356,7 @@ write_tsv_dataset <- function(dataset, batch_size = 1024L, na = "", eol = "\n", - quote = "Needed") { + quote = c("Needed", "AllValid", "None")) { if (!missing(max_rows_per_file) && missing(max_rows_per_group) && max_rows_per_group > max_rows_per_file) { max_rows_per_group <- max_rows_per_file } diff --git a/r/tests/testthat/test-dataset-write.R b/r/tests/testthat/test-dataset-write.R index 95ae046d1160..1719cafb88c1 100644 --- a/r/tests/testthat/test-dataset-write.R +++ b/r/tests/testthat/test-dataset-write.R @@ -935,21 +935,20 @@ test_that("Dataset can write flat files using readr::write_csv() options.", { close(con) # 0d and 0a are the character codes for CRLF (https://www.asciitable.com) - expect_equal(as.character(header[4:5]), c("0d", "0a")) + expect_equal(header[4:5], as.raw(c(0x0d, 0x0a))) dst_dir <- make_temp_dir() expect_error( write_dataset(df, dst_dir, format = "csv", include_header = FALSE, delim = ";"), - "Can't write dataset with both Arrow options and readr options." + "Use either Arrow write options or readr write options, not both" ) dst_dir <- make_temp_dir() - write_dataset(df, dst_dir, format = "csv", quote = "AllValid") + write_dataset(df, dst_dir, format = "csv", quoting_style = "AllValid") ds <- open_dataset(dst_dir, format = "csv") expect_equal(df, ds |> collect()) expect_error( - write_dataset(df, dst_dir, format = "csv", quote = "foobar"), - "quoting_style must be 1 of 'Needed', 'AllValid' or 'None'" + write_dataset(df, dst_dir, format = "csv", quoting_style = "foobar") ) expect_error( @@ -984,7 +983,7 @@ test_that("Dataset write wrappers can write flat files using readr::write_csv() header <- readBin(con <- file(paste0(dst_dir, "/part-0.csv"), "rb"), "raw", n = 5) close(con) # 0d and 0a are the character codes for CRLF (https://www.asciitable.com) - expect_equal(as.character(header[4:5]), c("0d", "0a")) + expect_equal(header[4:5], as.raw(c(0x0d, 0x0a))) df2 <- tibble(x = "") dst_dir <- make_temp_dir() @@ -992,7 +991,7 @@ test_that("Dataset write wrappers can write flat files using readr::write_csv() header <- readBin(con <- file(paste0(dst_dir, "/part-0.tsv"), "rb"), "raw", n = 5) close(con) # 0d and 0a are the character codes for CRLF (https://www.asciitable.com) - expect_equal(as.character(header[4:5]), c("0d", "0a")) + expect_equal(header[4:5], as.raw(c(0x0d, 0x0a))) dst_dir <- make_temp_dir() write_csv_dataset(df, dst_dir, quote = "AllValid", delim = ";") @@ -1001,6 +1000,6 @@ test_that("Dataset write wrappers can write flat files using readr::write_csv() dst_dir <- make_temp_dir() write_tsv_dataset(df, dst_dir, quote = "AllValid", eol = "\r\n") - ds <- open_dataset(dst_dir, format = "tsv") + ds <- open_dataset(dst_dir, format = "tsv", quote_char = "\"") expect_equal(df, ds |> collect()) }) From 6b9f20dd7db6b5c5f647dbc72938819bd63cff56 Mon Sep 17 00:00:00 2001 From: David Greiss Date: Thu, 10 Aug 2023 11:16:28 -0400 Subject: [PATCH 10/17] consistent readr opts for quote style --- r/R/csv.R | 6 +++++- r/R/dataset-write.R | 27 +++++++++++++++++++++------ r/tests/testthat/test-dataset-write.R | 6 +++--- 3 files changed, 29 insertions(+), 10 deletions(-) diff --git a/r/R/csv.R b/r/R/csv.R index 82bdd78a3f9c..5f3992fdd84f 100644 --- a/r/R/csv.R +++ b/r/R/csv.R @@ -515,7 +515,11 @@ readr_to_csv_write_options <- function(col_names = TRUE, delim = ",", na = "", eol = "\n", - quote = "Needed") { + quote = c("needed", "all", "none")) { + quoting_style_arrow_opts <- c("Needed", "AllValid", "None") + quote <- match(match.arg(quote), c("needed", "all", "none")) + quote <- quoting_style_arrow_opts[quote] + CsvWriteOptions$create( include_header = col_names, batch_size = batch_size, diff --git a/r/R/dataset-write.R b/r/R/dataset-write.R index c4af9f37b337..a29deaa808f7 100644 --- a/r/R/dataset-write.R +++ b/r/R/dataset-write.R @@ -242,11 +242,11 @@ write_dataset <- function(dataset, #' The default is an empty string `""`. #' @param eol the end of line character to use for ending rows. The default is `"\n"`. #' @param quote How to handle fields which contain characters that need to be quoted. -#' - `Needed` - Only enclose values in quotes which need them, because their CSV rendering can +#' - `needed` - Only enclose values in quotes which need them, because their CSV rendering can #' contain quotes itself (e.g. strings or binary values) (the default) -#' - `AllValid` - Enclose all valid values in quotes. Nulls are not quoted. May cause readers to +#' - `all` - Enclose all valid values in quotes. Nulls are not quoted. May cause readers to #' interpret all values as strings if schema is inferred. -#' - `None` - Do not enclose any values in quotes. Prevents values from containing quotes ("), +#' - `none` - Do not enclose any values in quotes. Prevents values from containing quotes ("), #' cell delimiters (,) or line endings (\\r, \\n), (following RFC4180). If values #' contain these characters, an error is caused when attempting to write. #' @return The input `dataset`, invisibly. @@ -269,10 +269,15 @@ write_delim_dataset <- function(dataset, delim = ",", na = "", eol = "\n", - quote = c("Needed", "AllValid", "None")) { + quote = c("needed", "all", "none")) { if (!missing(max_rows_per_file) && missing(max_rows_per_group) && max_rows_per_group > max_rows_per_file) { max_rows_per_group <- max_rows_per_file } + + quoting_style_arrow_opts <- c("Needed", "AllValid", "None") + quote <- match(match.arg(quote), c("needed", "all", "none")) + quote <- quoting_style_arrow_opts[quote] + write_dataset( dataset = dataset, path = path, @@ -313,10 +318,15 @@ write_csv_dataset <- function(dataset, delim = ",", na = "", eol = "\n", - quote = c("Needed", "AllValid", "None")) { + quote = c("needed", "all", "none")) { if (!missing(max_rows_per_file) && missing(max_rows_per_group) && max_rows_per_group > max_rows_per_file) { max_rows_per_group <- max_rows_per_file } + + quoting_style_arrow_opts <- c("Needed", "AllValid", "None") + quote <- match(match.arg(quote), c("needed", "all", "none")) + quote <- quoting_style_arrow_opts[quote] + write_dataset( dataset = dataset, path = path, @@ -356,10 +366,15 @@ write_tsv_dataset <- function(dataset, batch_size = 1024L, na = "", eol = "\n", - quote = c("Needed", "AllValid", "None")) { + quote = c("needed", "all", "none")) { if (!missing(max_rows_per_file) && missing(max_rows_per_group) && max_rows_per_group > max_rows_per_file) { max_rows_per_group <- max_rows_per_file } + + quoting_style_arrow_opts <- c("Needed", "AllValid", "None") + quote <- match(match.arg(quote), c("needed", "all", "none")) + quote <- quoting_style_arrow_opts[quote] + write_dataset( dataset = dataset, path = path, diff --git a/r/tests/testthat/test-dataset-write.R b/r/tests/testthat/test-dataset-write.R index 1719cafb88c1..033253c01c29 100644 --- a/r/tests/testthat/test-dataset-write.R +++ b/r/tests/testthat/test-dataset-write.R @@ -994,12 +994,12 @@ test_that("Dataset write wrappers can write flat files using readr::write_csv() expect_equal(header[4:5], as.raw(c(0x0d, 0x0a))) dst_dir <- make_temp_dir() - write_csv_dataset(df, dst_dir, quote = "AllValid", delim = ";") + write_csv_dataset(df, dst_dir, quote = "all", delim = ";") ds <- open_dataset(dst_dir, format = "csv", delim = ";") expect_equal(df, ds |> collect()) dst_dir <- make_temp_dir() - write_tsv_dataset(df, dst_dir, quote = "AllValid", eol = "\r\n") - ds <- open_dataset(dst_dir, format = "tsv", quote_char = "\"") + write_tsv_dataset(df, dst_dir, quote = "all", eol = "\r\n") + ds <- open_dataset(dst_dir, format = "tsv") expect_equal(df, ds |> collect()) }) From 43c6ce7a7e37f8475b0e927419afd6c2fcb78cb2 Mon Sep 17 00:00:00 2001 From: David Greiss Date: Fri, 11 Aug 2023 08:54:12 -0400 Subject: [PATCH 11/17] Add tests --- r/tests/testthat/test-dataset-write.R | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/r/tests/testthat/test-dataset-write.R b/r/tests/testthat/test-dataset-write.R index 033253c01c29..d88440068c97 100644 --- a/r/tests/testthat/test-dataset-write.R +++ b/r/tests/testthat/test-dataset-write.R @@ -947,6 +947,9 @@ test_that("Dataset can write flat files using readr::write_csv() options.", { ds <- open_dataset(dst_dir, format = "csv") expect_equal(df, ds |> collect()) + lines <- paste(readLines(paste0(dst_dir, "/part-0.csv")), sep = "\n") + expect_equal(lines[2], "\"1\",\"1\",\"true\",\"a\"") + expect_error( write_dataset(df, dst_dir, format = "csv", quoting_style = "foobar") ) @@ -998,8 +1001,14 @@ test_that("Dataset write wrappers can write flat files using readr::write_csv() ds <- open_dataset(dst_dir, format = "csv", delim = ";") expect_equal(df, ds |> collect()) + lines <- paste(readLines(paste0(dst_dir, "/part-0.csv")), sep = "\n") + expect_equal(lines[2], "\"1\";\"1\";\"true\";\"a\"") + dst_dir <- make_temp_dir() write_tsv_dataset(df, dst_dir, quote = "all", eol = "\r\n") ds <- open_dataset(dst_dir, format = "tsv") expect_equal(df, ds |> collect()) + + lines <- paste(readLines(paste0(dst_dir, "/part-0.tsv")), sep = "\n") + expect_equal(lines[2], "\"1\"\t\"1\"\t\"true\"\t\"a\"") }) From d9117775edd991a979e6d71b73959c1a387241b3 Mon Sep 17 00:00:00 2001 From: David Greiss Date: Fri, 11 Aug 2023 09:01:24 -0400 Subject: [PATCH 12/17] Update docs --- r/R/dataset-write.R | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/r/R/dataset-write.R b/r/R/dataset-write.R index a29deaa808f7..d13a10833c56 100644 --- a/r/R/dataset-write.R +++ b/r/R/dataset-write.R @@ -242,8 +242,8 @@ write_dataset <- function(dataset, #' The default is an empty string `""`. #' @param eol the end of line character to use for ending rows. The default is `"\n"`. #' @param quote How to handle fields which contain characters that need to be quoted. -#' - `needed` - Only enclose values in quotes which need them, because their CSV rendering can -#' contain quotes itself (e.g. strings or binary values) (the default) +#' - `needed` - Enclose all strings and binary values in quotes which need them, because their CSV rendering can +#' contain quotes itself (the default) #' - `all` - Enclose all valid values in quotes. Nulls are not quoted. May cause readers to #' interpret all values as strings if schema is inferred. #' - `none` - Do not enclose any values in quotes. Prevents values from containing quotes ("), From f8828350cc28c921667d36c71bfa08a461fb7947 Mon Sep 17 00:00:00 2001 From: Nic Crane Date: Tue, 15 Aug 2023 15:18:19 +0100 Subject: [PATCH 13/17] Update r/_pkgdown.yml --- r/_pkgdown.yml | 1 - 1 file changed, 1 deletion(-) diff --git a/r/_pkgdown.yml b/r/_pkgdown.yml index b3e82851867a..57c21e3c0f2c 100644 --- a/r/_pkgdown.yml +++ b/r/_pkgdown.yml @@ -138,7 +138,6 @@ articles: - developers/data_object_layout reference: - - title: Read datasets desc: > Open multi-file datasets as Arrow Dataset objects. From e5161558936a247c92bbace61d648770e26b5077 Mon Sep 17 00:00:00 2001 From: David Greiss Date: Thu, 17 Aug 2023 14:26:35 -0400 Subject: [PATCH 14/17] Remove test Co-authored-by: Nic Crane --- r/tests/testthat/test-dataset-write.R | 4 ---- 1 file changed, 4 deletions(-) diff --git a/r/tests/testthat/test-dataset-write.R b/r/tests/testthat/test-dataset-write.R index d88440068c97..4b1c11cef1d2 100644 --- a/r/tests/testthat/test-dataset-write.R +++ b/r/tests/testthat/test-dataset-write.R @@ -950,10 +950,6 @@ test_that("Dataset can write flat files using readr::write_csv() options.", { lines <- paste(readLines(paste0(dst_dir, "/part-0.csv")), sep = "\n") expect_equal(lines[2], "\"1\",\"1\",\"true\",\"a\"") - expect_error( - write_dataset(df, dst_dir, format = "csv", quoting_style = "foobar") - ) - expect_error( write_dataset(df, dst_dir, format = "tsv", delimiter = ";"), "Can't set a delimiter for the tsv format." From 251c4d6a25f13c30c3fa039bf4916f1396d36c25 Mon Sep 17 00:00:00 2001 From: David Greiss Date: Thu, 17 Aug 2023 14:26:48 -0400 Subject: [PATCH 15/17] Update r/tests/testthat/test-dataset-write.R Co-authored-by: Nic Crane --- r/tests/testthat/test-dataset-write.R | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/r/tests/testthat/test-dataset-write.R b/r/tests/testthat/test-dataset-write.R index 4b1c11cef1d2..0dea821a0bbd 100644 --- a/r/tests/testthat/test-dataset-write.R +++ b/r/tests/testthat/test-dataset-write.R @@ -1007,4 +1007,13 @@ test_that("Dataset write wrappers can write flat files using readr::write_csv() lines <- paste(readLines(paste0(dst_dir, "/part-0.tsv")), sep = "\n") expect_equal(lines[2], "\"1\"\t\"1\"\t\"true\"\t\"a\"") + + dst_dir <- make_temp_dir() + write_tsv_dataset(df, dst_dir, na = "NOVALUE") + ds <- open_dataset(dst_dir, format = "tsv") |> collect() + + expect_equal( + ds$lgl, + c("true", "false", "NOVALUE", "true", "false", "true", "false", "NOVALUE", "true", "false") + ) }) From 32cc99ebe66507ac1251cbfecb740e5afaf1a18d Mon Sep 17 00:00:00 2001 From: Nic Crane Date: Fri, 25 Aug 2023 10:20:23 +0100 Subject: [PATCH 16/17] Fix docs typo --- r/R/dataset-write.R | 2 +- r/man/write_delim_dataset.Rd | 55 +++++++++++++++++++++++++++--------- 2 files changed, 43 insertions(+), 14 deletions(-) diff --git a/r/R/dataset-write.R b/r/R/dataset-write.R index d13a10833c56..288da4ffde7c 100644 --- a/r/R/dataset-write.R +++ b/r/R/dataset-write.R @@ -233,7 +233,7 @@ write_dataset <- function(dataset, #' The `write_*_dataset()` are a family of wrappers around [write_dataset] to allow for easy switching #' between functions for writing datasets. #' -#' @inheritParams [write_dataset()] +#' @inheritParams write_dataset #' @param col_names Whether to write an initial header line with column names. #' @param batch_size Maximum number of rows processed at a time. Default is 1024L. #' @param delim Delimiter used to separate values. Defaults to `","` for `write_delim_dataset()` and diff --git a/r/man/write_delim_dataset.Rd b/r/man/write_delim_dataset.Rd index 7430ade97d4c..2dcd9707dca0 100644 --- a/r/man/write_delim_dataset.Rd +++ b/r/man/write_delim_dataset.Rd @@ -18,8 +18,12 @@ write_delim_dataset( max_rows_per_file = 0L, min_rows_per_group = 0L, max_rows_per_group = bitwShiftL(1, 20), - delimiter = ",", - ... + col_names = TRUE, + batch_size = 1024L, + delim = ",", + na = "", + eol = "\\n", + quote = c("needed", "all", "none") ) write_csv_dataset( @@ -34,7 +38,12 @@ write_csv_dataset( max_rows_per_file = 0L, min_rows_per_group = 0L, max_rows_per_group = bitwShiftL(1, 20), - ... + col_names = TRUE, + batch_size = 1024L, + delim = ",", + na = "", + eol = "\\n", + quote = c("needed", "all", "none") ) write_tsv_dataset( @@ -49,7 +58,11 @@ write_tsv_dataset( max_rows_per_file = 0L, min_rows_per_group = 0L, max_rows_per_group = bitwShiftL(1, 20), - ... + col_names = TRUE, + batch_size = 1024L, + na = "", + eol = "\\n", + quote = c("needed", "all", "none") ) } \arguments{ @@ -67,9 +80,9 @@ use the current \code{group_by()} columns.} \item{basename_template}{string template for the names of files to be written. Must contain \code{"{i}"}, which will be replaced with an autoincremented -integer to generate basenames of datafiles. For example, \code{"part-{i}.csv"} -will yield \verb{"part-0.csv", ...}. -If not specified, it defaults to \code{"part-{i}.csv"}.} +integer to generate basenames of datafiles. For example, \code{"part-{i}.arrow"} +will yield \verb{"part-0.arrow", ...}. +If not specified, it defaults to \code{"part-{i}."}.} \item{hive_style}{logical: write partition segments as Hive-style (\code{key1=value1/key2=value2/file.ext}) or as just bare values. Default is \code{TRUE}.} @@ -110,15 +123,31 @@ group and when this number of rows is exceeded, it is split and the next set of rows is written to the next group. This value must be set such that it is greater than \code{min_rows_per_group}. Default is 1024 * 1024.} -\item{delimiter}{Delimiter used to separate values. Defaults to \code{","} for \code{write_delim_dataset()} and -\code{write_csv_dataset()}, and \verb{"\\t} for \code{write_tsv_dataset()}. Cannot be changed for \code{write_csv_dataset()} -and \code{write_tsv_dataset()}.} +\item{col_names}{Whether to write an initial header line with column names.} -\item{...}{additional format-specific arguments. For available CSV -options, see \link{CsvWriteOptions}.} +\item{batch_size}{Maximum number of rows processed at a time. Default is 1024L.} + +\item{delim}{Delimiter used to separate values. Defaults to \code{","} for \code{write_delim_dataset()} and +\code{write_csv_dataset()}, and \verb{"\\t} for \code{write_tsv_dataset()}. Cannot be changed for \code{write_tsv_dataset()}.} + +\item{na}{a character vector of strings to interpret as missing values. Quotes are not allowed in this string. +The default is an empty string \code{""}.} + +\item{eol}{the end of line character to use for ending rows. The default is \code{"\\n"}.} + +\item{quote}{How to handle fields which contain characters that need to be quoted. +\itemize{ +\item \code{needed} - Enclose all strings and binary values in quotes which need them, because their CSV rendering can +contain quotes itself (the default) +\item \code{all} - Enclose all valid values in quotes. Nulls are not quoted. May cause readers to +interpret all values as strings if schema is inferred. +\item \code{none} - Do not enclose any values in quotes. Prevents values from containing quotes ("), +cell delimiters (,) or line endings (\\r, \\n), (following RFC4180). If values +contain these characters, an error is caused when attempting to write. +}} } \value{ -The input \code{dataset}, invisibly +The input \code{dataset}, invisibly. } \description{ The \verb{write_*_dataset()} are a family of wrappers around \link{write_dataset} to allow for easy switching From 7c52c68a7bd2d576f5ca12669dbb1adcb67a725a Mon Sep 17 00:00:00 2001 From: Nic Crane Date: Fri, 25 Aug 2023 11:35:05 +0100 Subject: [PATCH 17/17] appease the linter --- r/tests/testthat/test-dataset-write.R | 1 - 1 file changed, 1 deletion(-) diff --git a/r/tests/testthat/test-dataset-write.R b/r/tests/testthat/test-dataset-write.R index 0dea821a0bbd..e2c3c68b5022 100644 --- a/r/tests/testthat/test-dataset-write.R +++ b/r/tests/testthat/test-dataset-write.R @@ -1007,7 +1007,6 @@ test_that("Dataset write wrappers can write flat files using readr::write_csv() lines <- paste(readLines(paste0(dst_dir, "/part-0.tsv")), sep = "\n") expect_equal(lines[2], "\"1\"\t\"1\"\t\"true\"\t\"a\"") - dst_dir <- make_temp_dir() write_tsv_dataset(df, dst_dir, na = "NOVALUE") ds <- open_dataset(dst_dir, format = "tsv") |> collect()